Advertisement
kartikkukreja

Dijkstra's single source shortest path algorithm

May 23rd, 2013
372
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 5.05 KB | None | 0 0
  1. /*
  2.  *  Input file format:
  3.  *      V E
  4.  *      u1 v1 c1
  5.  *      u2 v2 c2
  6.  *          :
  7.  *      ue ve ce
  8.  *      s
  9.  *      t1
  10.  *      t2
  11.  *      :
  12.  *      -1
  13.  *  The first line contains two integers V & E, the number of vertices and the number of edges respectively.
  14.  *  E lines follow, each containing 3 integers ui, vi, ci representing the directed edge ui -> vi having cost ci.
  15.  *  (E + 2)nd line contains an integer s, representing the source vertex.
  16.  *  Each next line contains an integer t, the target vertex, which represents a query to find the shortest path from s to t.
  17.  *  The queries end with a single line containing -1.
  18.  *
  19.  *  Output format:
  20.  *      For each query t, the program writes two lines, the first describes the shortest path from s to t
  21.  *      and the second describes the cost of the shortest path from s to t.
  22.  */
  23.  
  24. #include <cstdio>
  25. #include <climits>
  26. #include <vector>
  27. #include <stack>
  28. using namespace std;
  29.  
  30. /*
  31.  * Indexed min priority queue
  32.  * Supports insertion in O(log N), deletion of any key (regardless of whether
  33.  * the key is the minimum key or not) in O(log N) and changes to key values
  34.  * in O(log N), where N is the number of
  35.  * elements currently in the PQ
  36.  */
  37. class MinIndexedPQ {
  38.     int NMAX, N, *heap, *index, *keys;
  39.  
  40.     void swap(int i, int j) {
  41.         int t = heap[i]; heap[i] = heap[j]; heap[j] = t;
  42.         index[heap[i]] = i; index[heap[j]] = j;
  43.     }
  44.     void bubbleUp(int k)    {
  45.         while(k > 1 && keys[heap[k/2]] > keys[heap[k]])   {
  46.             swap(k, k/2);
  47.             k = k/2;
  48.         }
  49.     }
  50.     void bubbleDown(int k)  {
  51.         int j;
  52.         while(2*k <= N) {
  53.             j = 2*k;
  54.             if(j < N && keys[heap[j]] > keys[heap[j+1]])
  55.                 j++;
  56.             if(keys[heap[k]] <= keys[heap[j]])
  57.                 break;
  58.             swap(k, j);
  59.             k = j;
  60.         }
  61.     }
  62. public:
  63.     // Create an empty MinIndexedPQ which can contain atmost NMAX elements
  64.     MinIndexedPQ(int NMAX)  {
  65.         this->NMAX = NMAX;
  66.         N = 0;
  67.         keys = new int[NMAX + 1];
  68.         heap = new int[NMAX + 1];
  69.         index = new int[NMAX + 1];
  70.         for(int i = 0; i <= NMAX; i++)
  71.             index[i] = -1;
  72.     }
  73.     ~MinIndexedPQ() {
  74.         delete [] keys;
  75.         delete [] heap;
  76.         delete [] index;
  77.     }
  78.     // check if the PQ is empty
  79.     bool isEmpty()  {
  80.         return N == 0;
  81.     }
  82.     // check if i is an index on the PQ
  83.     bool contains(int i)    {
  84.         return index[i] != -1;
  85.     }
  86.     // associate key with index i; 0 < i < NMAX
  87.     void insert(int i, int key) {
  88.         N++;
  89.         index[i] = N;
  90.         heap[N] = i;
  91.         keys[i] = key;
  92.         bubbleUp(N);
  93.     }
  94.     // delete the minimal key and return its associated index
  95.     // Warning: Don't try to read from this index after calling this function
  96.     int deleteMin() {
  97.         int min = heap[1];
  98.         swap(1, N--);
  99.         bubbleDown(1);
  100.         index[min] = -1;
  101.         heap[N+1] = -1;
  102.         return min;
  103.     }
  104.     // decrease the key associated with index i to the specified value
  105.     void decreaseKey(int i, int key)    {
  106.         keys[i] = key;
  107.         bubbleUp(index[i]);
  108.     }
  109. };
  110.  
  111. // representation of directed edge to vertex 'to' having weight 'weight'
  112. struct Edge {
  113.     int to, weight;
  114. };
  115.  
  116. typedef vector <Edge> adjList;
  117.  
  118. int main()  {
  119.     int V, E, i, N, u, v, cost, *dist, *edgeTo, s;
  120.     adjList *G;
  121.     stack <int> path;
  122.  
  123.     // Assuming vertices are labeled 0...V-1
  124.     freopen("input.txt", "r", stdin);
  125.  
  126.     scanf("%d %d", &V, &E); // Enter the number of vertices and edges
  127.     G = new adjList[V];
  128.     for(i=0; i<E; i++)  {   // Enter E directed edges u -> v having weight 'cost'
  129.         scanf("%d %d %d", &u, &v, &cost);
  130.         G[u].push_back((Edge){v, cost});    // add edge to adjacency list of u
  131.     }
  132.     scanf("%d", &s);    // Enter the source vertex
  133.  
  134.     dist = new int[V];
  135.     for(i=0; i<V; i++)
  136.         dist[i] = INT_MAX;
  137.     dist[s] = 0;
  138.     edgeTo = new int[V];
  139.     edgeTo[s] = s;
  140.  
  141.     MinIndexedPQ pq(V);
  142.     pq.insert(s, 0);
  143.  
  144.     while(!pq.isEmpty())    {
  145.         u = pq.deleteMin();
  146.         for(adjList::iterator it = G[u].begin(); it != G[u].end(); it++)    {
  147.             v = it->to;
  148.             cost = dist[u] + it->weight;
  149.             if(cost < dist[v])    {
  150.                 dist[v] = cost;
  151.                 edgeTo[v] = u;
  152.                 if(pq.contains(v)) pq.decreaseKey(v, cost);
  153.                 else pq.insert(v, cost);
  154.             }
  155.         }
  156.     }
  157.  
  158.     while(true) {
  159.         scanf("%d", &v);    // Enter the target vertex v
  160.         if(v < 0) break;
  161.  
  162.         u = v;
  163.         while(edgeTo[u] != u)   {
  164.             path.push(edgeTo[u]);
  165.             u = edgeTo[u];
  166.         }
  167.         while(!path.empty())    {   // print path from s to v
  168.             printf("%d-", path.top());
  169.             path.pop();
  170.         }
  171.         printf("%d\n", v);
  172.         printf("%d\n", dist[v]);    // print cost of shortest path from s to v
  173.     }
  174.  
  175.     delete [] dist;
  176.     delete [] edgeTo;
  177.     delete [] G;
  178.  
  179.     return 0;
  180. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement