Advertisement
AmidamaruZXC

Untitled

Jun 23rd, 2020
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <list>
  4. #include <queue>
  5.  
  6. using namespace std;
  7.  
  8. # define INF 0x3f3f3f3f
  9.  
  10. typedef pair<int, int> iPair;
  11.  
  12.  
  13. class Graph
  14. {
  15.     int V;
  16.  
  17.  
  18.     list< pair<int, int> >* adj;
  19.  
  20. public:
  21.     Graph(int V);
  22.  
  23.  
  24.     void addEdge(int u, int v, int w);
  25.  
  26.  
  27.     void shortestPath(int s);
  28. };
  29.  
  30.  
  31. Graph::Graph(int V)
  32. {
  33.     this->V = V;
  34.     adj = new list<iPair>[V];
  35. }
  36.  
  37. void Graph::addEdge(int u, int v, int w)
  38. {
  39.     adj[u].push_back(make_pair(v, w));
  40.     adj[v].push_back(make_pair(u, w));
  41. }
  42.  
  43. void Graph::shortestPath(int src)
  44. {
  45.     priority_queue< iPair, vector <iPair>, greater<iPair> > pq;
  46.  
  47.     vector<int> dist(V, INF);
  48.  
  49.     pq.push(make_pair(0, src));
  50.     dist[src] = 0;
  51.  
  52.     while (!pq.empty())
  53.     {
  54.         int u = pq.top().second;
  55.         pq.pop();
  56.  
  57.         list< pair<int, int> >::iterator i;
  58.         for (i = adj[u].begin(); i != adj[u].end(); ++i)
  59.         {
  60.             int v = (*i).first;
  61.             int weight = (*i).second;
  62.  
  63.             if (dist[v] > dist[u] + weight)
  64.             {
  65.                 dist[v] = dist[u] + weight;
  66.                 pq.push(make_pair(dist[v], v));
  67.             }
  68.         }
  69.     }
  70.  
  71.     for (int i = 1; i < V; ++i)
  72.         cout << dist[i] << " ";
  73. }
  74.  
  75.  
  76. int main()
  77. {
  78.     int N, M, A, B, W;
  79.     cin >> N;
  80.     cin >> M;
  81.     Graph g(M);
  82.     for (int i = 0; i < M; i++)
  83.     {
  84.         cin >> A >> W >> B;
  85.         A -= 1;
  86.         B -= 1;
  87.         g.addEdge(A, B, W);
  88.     }
  89.     g.shortestPath(0);
  90.  
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement