STANAANDREY

dijkstra

Mar 9th, 2021 (edited)
427
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define newline '\n'
  3. using namespace std;
  4. ifstream fin("dijkstra.in");
  5. ofstream fout("dijkstra.out");
  6. ///***********************
  7. const int NMAX = 5e4 + 5;
  8. const int OO = (1 << 30);
  9. int dis[NMAX];
  10. bool vis[NMAX];
  11. class item
  12. {
  13. public:
  14.     int node;
  15.     int dis;
  16.     bool operator < (const item &other) const noexcept
  17.     {
  18.         return this->dis > other.dis;
  19.     }
  20. };
  21. array<vector<item>, NMAX> graph;
  22. priority_queue<item> q;
  23. int n, m;
  24.  
  25. void read()
  26. {
  27.     fin >> n >> m;
  28.     for (int i = 1; i <= m; i++)
  29.     {
  30.         int a, b, c;
  31.         fin >> a >> b >> c;
  32.         graph[a].push_back({b, c});
  33.     }
  34. }
  35.  
  36. void dijkstra(int start)
  37. {
  38.     item e;
  39.     fill(dis, dis + NMAX, OO);
  40.     dis[start] = 0;
  41.     q.push({1, 0});
  42.     while (!q.empty())
  43.     {
  44.         e = q.top();
  45.         q.pop();
  46.         if (vis[e.node])
  47.             continue;
  48.         vis[e.node] = true;
  49.         for (auto nei : graph[e.node])
  50.         {
  51.             if (dis[nei.node] > nei.dis + dis[e.node])
  52.             {
  53.                 dis[nei.node] = nei.dis + dis[e.node];
  54.                 nei.dis = dis[nei.node];
  55.                 q.push(nei);
  56.             }
  57.         }
  58.     }
  59. }
  60.  
  61. void display()
  62. {
  63.     for (int i = 2; i <= n; i++)
  64.         if (dis[i] == OO)
  65.             fout << 0 << ' ';
  66.         else
  67.             fout << dis[i] << ' ';
  68. }
  69.  
  70. int main()
  71. {
  72.     read();
  73.     dijkstra(1);
  74.     display();
  75.     fout.close();
  76.     return 0;
  77. }
Add Comment
Please, Sign In to add comment