Advertisement
sleepy_coder

Dijkstra

Oct 11th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. #define M 110
  2. VII adjList[M];//node, edeg_cost
  3. int dist[M];//you can make it local to function
  4. int nodes, edges;
  5.  
  6. struct data{//kinda of edges
  7.     int city, dist;
  8.     data(int dist, int city){ this->city = city, this->dist = dist; }
  9.     bool operator < (const data& rhs) const {
  10.         return rhs.dist < this->dist;//ultai dilam..katakati :)
  11.     }
  12. };
  13.  
  14. int dijkstra(int source, int destination){
  15.     FOR(i, 1, nodes){
  16.         dist[i] = INF;
  17.         //sort(ALL(adjList[i]), [](const PII& a, const PII& b){ return a.second < b.second; });
  18.     }
  19.    
  20.  
  21.     priority_queue< data > pq;
  22.     pq.push(data(0, source));
  23.     dist[source] = 0;
  24.  
  25.     while(!pq.empty()){
  26.         data u = pq.top();
  27.         pq.pop();
  28.         int uCost = dist[u.city];
  29.  
  30.         for(auto& item: adjList[u.city]){
  31.             data v(item.second + uCost, item.first);
  32.             if(dist[v.city] > v.dist){
  33.  
  34.                 dist[v.city] = v.dist;
  35.                 pq.push(v);
  36.             }
  37.         }  
  38.     }
  39.  
  40.     return dist[destination];
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement