Last active
February 4, 2018 17:56
-
-
Save HarshVardhanKumar/b1a84761ce802f7c7a683e993ec1d2f2 to your computer and use it in GitHub Desktop.
C++ implementation of Dijkshtra's Algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Created by Harsh Vardhan Kumar on 29-01-2018. | |
// | |
#include <iostream> | |
#include <set> | |
#include <vector> | |
using namespace std ; | |
const int inf = 1000000 ; | |
const int nil = -1000000 ; | |
class node { | |
public: | |
int parent; int key; int node_val ; | |
bool operator < (const node & node2) const { | |
if(this->key < node2.key) return this->key<node2.key ; | |
else if(this->key == node2.key) return this->node_val<node2.node_val ; | |
else return this->key < node2.key && this->node_val < node2.node_val ; | |
//else return this->key < node2.key && this->node_val > node2.node_val ; | |
} | |
node(int parentv, int keyv, int node_valv) { | |
parent = parentv ; | |
key = keyv ; | |
node_val = node_valv ; | |
} | |
node() {} | |
}; | |
int main() { | |
multiset <node> Q ; | |
vector<vector<pair<int, int> > > adList ; | |
int no_nodes ; cin>>no_nodes ; | |
char nod[no_nodes] ; | |
char nodeval = 'a'-1 ; | |
for(int i = 0 ; i<no_nodes; i++) { | |
nodeval++ ; | |
nod[i] = nodeval ; | |
} | |
node nodes[no_nodes] ; | |
for(int i = 0 ; i<no_nodes; i++) { | |
vector<pair<int, int> > v ; | |
adList.push_back(v) ; | |
node s(nil,inf+i, i) ; | |
nodes[i] = s ; | |
} | |
int w ; | |
for(int i = 0 ; i<no_nodes; i++) { | |
for(int j = 0 ; j<no_nodes; j++) { | |
cin>>w ; | |
if(w != inf) { | |
adList[i].emplace_back(make_pair(j, w)) ; | |
} | |
} | |
} | |
int source; cin>>source ; | |
nodes[source].key = 0 ; | |
for(int i = 0 ; i<no_nodes; i++) { | |
Q.insert(nodes[i]) ; | |
} | |
while(!Q.empty()) { | |
node u = *Q.begin(); | |
int u_index = u.node_val ; | |
nodes[u_index] = u ; | |
Q.erase(nodes[u_index]) ; | |
for(pair<int, int> p : adList[u_index]) { | |
node v = nodes[p.first] ; | |
if(v.key > u.key+p.second) { | |
Q.erase(v) ; | |
v.parent = u_index ; | |
v.key = p.second+u.key ; | |
nodes[v.node_val] = v ; | |
Q.insert(v) ; | |
} | |
} | |
} | |
for(node n : nodes) { | |
if(n.parent>=0) | |
cout<<nod[n.node_val]<<" ("<<n.key<<") -- "<<nod[n.parent]<<endl ; | |
else cout<<nod[n.node_val]<<" ("<<n.key<<") -- "<<"Nil "<<endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment