Advertisement
Waliul

Not the best

Apr 21st, 2021
910
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define inf 1061109567
  5. #define inf_m 63
  6. #define mx 5005
  7. struct node
  8. {
  9.     int u, cost;
  10.     node(){;}
  11.     node(int _u, int _cost)
  12.     {
  13.         u = _u;
  14.         cost = _cost;
  15.     }
  16. };
  17. bool operator < (node A, node B)
  18. {
  19.     return B.cost < A.cost;
  20. }
  21. vector<node>adj[mx];
  22. int dis_f[mx], dis_s[mx];
  23.  
  24. void dijkstra(int s, int e)
  25. {
  26.     memset(dis_f, 63, sizeof(dis_f));
  27.     memset(dis_s, 63, sizeof(dis_s));
  28.     priority_queue<node>pq;
  29.     dis_f[s] = 0;
  30.     pq.push(node(s, 0));
  31.     node top, temp;
  32.     while(!pq.empty())
  33.     {
  34.         top = pq.top();
  35.         pq.pop();
  36.         if(top.cost > dis_s[top.u])
  37.             continue;
  38.         for(auto it : adj[top.u])
  39.         {
  40.             temp = it;
  41.             if(dis_f[it.u] > top.cost + it.cost)
  42.             {
  43.                 dis_s[it.u] = dis_f[it.u];
  44.                 dis_f[it.u] = top.cost + it.cost;
  45.                 pq.push(node(it.u, dis_f[it.u]));
  46.             }
  47.             else if(top.cost + it.cost > dis_f[it.u] && top.cost + it.cost < dis_s[it.u])
  48.             {
  49.                 dis_s[it.u] = top.cost + it.cost;
  50.                 pq.push(node(it.u, dis_s[it.u]));
  51.             }
  52.         }
  53.     }
  54. }
  55.  
  56. int main()
  57. {
  58.     int n, r, t, i, j, u, v, c;
  59.     scanf("%d", &t);
  60.     for(i = 1; i <= t; i++)
  61.     {
  62.         scanf("%d %d", &n, &r);
  63.         while(r--)
  64.         {
  65.             scanf("%d %d %d", &u, &v, &c);
  66.             adj[u].push_back(node(v, c));
  67.             adj[v].push_back(node(u, c));
  68.         }
  69.         dijkstra(1, n);
  70.         printf("Case %d: %d\n", i, dis_s[n]);
  71.         while(n)
  72.             adj[n--].clear();
  73.     }
  74.     return 0;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement