Saturday, September 29, 2012

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 I'm using to write it
Theory : [ http://en.wikipedia.org/wiki/Dijkstra's_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 that's all you need, I don't know for sure though. Let's see
Update : Here's 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\n");
  else printf("%d\n",res);
 } 
 
 return 0;
}

No comments:

Post a Comment

Post your comment here. If you want to say something about programming problems, scripts, software etc, please try to be as descriptive as possible.

Connect Rapoo MT750S with Linux (Tested on Manjaro)

 I bought this obvious copy of MX Master 2S in hopes of having the device switching functionality along with a lightweight body because I ha...