Wednesday, August 31, 2016

The Dijkstra Algorithm for Single Source Shortest Path

The Dijkstra Algorithm for Single Source Shortest Path


Currently the code is still under development. This is just to have the track of docs that Im using to write it
Theory : [ http://en.wikipedia.org/wiki/Dijkstras_algorithm ]
Priority queue (STL) : [ http://comsci.liu.edu/~jrodriguez/cs631sp08/c++priorityqueue.html ]
[ http://www.technical-recipes.com/2011/priority-queues-and-min-priority-queues-in-c/ ]
Till now it feels like thats all you need, I dont know for sure though. Lets see
Update : Heres a full code of a problem that I solved using this algorithm [UVA 10986]

#include <iostream>
#include <list>
#include <set>
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;

typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<ii> vii;

// based on TopCoder tutorial

#define tr(container, it) for(typeof(container.begin()) it = container.begin(); it != container.end(); it++)
#define INF 200000010

list<ii> G[30000];

int djk( int s, int t, int n ) {
vi D(n, INF);

set<ii> q;
D[s] = 0;
q.insert(ii(0,s));

while (!q.empty()) {


ii top = *q.begin();
q.erase(q.begin());
int v = top.second, d = top.first;

tr(G[v], it) {
int v2 = it->second, cost = it->first;
if (D[v2] > D[v] + cost) {
if (D[v2] != INF) {
q.erase(q.find(ii(D[v2],v2)));
}
D[v2] = D[v] + cost;
q.insert(ii(D[v2],v2));
}

}
}
return D[t];
}


int main( void ) {
int test, n, m, s, t, x, y, v, kase=1;
scanf("%d",&test);
while (test--) {
scanf("%d %d %d %d",&n,&m,&s,&t);
for (int i=0 ; i<=n ; i++) {
G[i].clear();
}
for (int i=0 ; i<m ; i++) {
scanf("%d %d %d",&x,&y,&v);
G[x].push_back(ii(v,y));
G[y].push_back(ii(v,x));
}
int res = djk(s,t,n);

printf("Case #%d: ",kase++);
if (res == INF) printf("unreachable ");
else printf("%d ",res);
}

return 0;
}


Go to link download