Guest User

Untitled

a guest
Jan 21st, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <list>
  4.  
  5. #define MAX_NODES 500
  6. #define INF 99999
  7.  
  8. using namespace std;
  9.  
  10. struct Node
  11. {
  12.     int cost, at;
  13.     Node(int a, int b): cost(a),at(b) {}
  14.     Node(){}
  15.  
  16. };
  17.  
  18. struct adj
  19. {
  20.     list<Node> rel;
  21. };
  22.  
  23. adj grafo[MAX_NODES];
  24. int dist[MAX_NODES],
  25.     N;
  26.  
  27. bool visited[MAX_NODES];
  28.  
  29. priority_queue<Node> pqueue;
  30.  
  31. bool operator<(const Node &leftNode, const Node &rightNode) {
  32.  if (leftNode.cost != rightNode.cost) return leftNode.cost > rightNode.cost;
  33.  if (leftNode.at != rightNode.at) return leftNode.at > rightNode.at;
  34.  return false;
  35. }
  36.  
  37.  
  38. void dijkstra()
  39. {
  40.     for( int i = 0; i < MAX_NODES ; i++)
  41.     {
  42.             dist[i] = INF;
  43.             visited[i] = false;
  44.     }
  45.    
  46.     Node tmp, tmp2;
  47.    
  48.     while(pqueue.size())
  49.     {
  50.         tmp = pqueue.top();
  51.         pqueue.pop();
  52.         if (visited[tmp.at]) continue;
  53.        
  54.         visited[tmp.at] = true;
  55.        
  56.         while(!grafo[tmp.at].rel.empty()) //relações implementadas com listas ligadas
  57.         {
  58.             tmp2 = grafo[tmp.at].rel.front();
  59.             grafo[tmp.at].rel.pop_front();
  60.            
  61.             if (dist[tmp2.at] > tmp.cost + tmp2.cost)
  62.                 {
  63.                     dist[tmp2.at] = tmp.cost + tmp2.cost;
  64.                     if(!visited[tmp2.at]) pqueue.push(Node(dist[tmp2.at],tmp2.at));
  65.                 }
  66.            
  67.         }
  68.        
  69.     }
  70.    
  71. }
  72.  
  73. int main()
  74. {
  75.     //input
  76.     int source,dest, weight, goal;
  77.    
  78.     cin >> N >> goal;
  79.    
  80.     for( int i = 0; i < N ; i++ )
  81.     {  
  82.         cin >> source >> dest >> weight;
  83.         grafo[source].rel.push_back (Node(weight,dest));
  84.     }
  85.    
  86.     pqueue.push(Node(0,goal));
  87.     dijkstra();
  88.    
  89.     for(int i = 1; i<=N;i++)
  90.         cout << i << " : " << dist[i] << endl;
  91.    
  92.     return 0;
  93. }
Add Comment
Please, Sign In to add comment