GastonFontenla

HackerRank: Dijkstra: Shortest Reach 2

Jun 5th, 2016
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4. #define ii pair<int, int>
  5.  
  6. using namespace std;
  7.  
  8. struct Arista
  9. {
  10.     int v, w;
  11. };
  12.  
  13. struct Grafo
  14. {
  15.     vector <vector <Arista> > adj;
  16.     vector <int> dist;
  17.  
  18.     void leer()
  19.     {
  20.         int n, m, a, b, w;
  21.         cin >> n >> m;
  22.         adj = vector <vector <Arista> > (n+1, vector <Arista> ());
  23.         dist = vector <int> (n+1, 999999999);
  24.  
  25.         Arista edge, edge2;
  26.         for(int i=0; i<m; i++)
  27.         {
  28.             cin >> a >> b >> w;
  29.             edge.v = b;
  30.             edge.w = w;
  31.             adj[a].push_back(edge);
  32.  
  33.             edge2.v = a;
  34.             edge2.w = w;
  35.             adj[b].push_back(edge2);
  36.         }
  37.         int s;
  38.         cin >> s;
  39.  
  40.         priority_queue<ii, vector <ii>, greater <ii> > pq;
  41.  
  42.         dist[s] = 0;
  43.         pq.push(ii(0, s));
  44.  
  45.         while(pq.size())
  46.         {
  47.             ii p = pq.top();
  48.             pq.pop();
  49.             s = p.second;
  50.             for(int i=0; i<adj[s].size(); i++)
  51.             {
  52.                 if(dist[s]+adj[s][i].w < dist[adj[s][i].v])
  53.                 {
  54.                     dist[adj[s][i].v] = dist[s]+adj[s][i].w;
  55.                     pq.push(ii(dist[adj[s][i].v], adj[s][i].v));
  56.                 }
  57.             }
  58.         }
  59.  
  60.         for(int i=1; i<dist.size(); i++)
  61.         {
  62.             if(dist[i] == 999999999)
  63.                 cout << -1 << " ";
  64.             else if(dist[i])
  65.                 cout << dist[i] << " ";
  66.         }
  67.  
  68.         cout << endl;
  69.  
  70.     }
  71.  
  72. };
  73.  
  74. int main()
  75. {
  76.     int tc;
  77.     cin >> tc;
  78.     while(tc--)
  79.     {
  80.         Grafo g;
  81.         g.leer();
  82.     }
  83.     return 0;
  84. }
Add Comment
Please, Sign In to add comment