Alex_tz307

Dijkstra

Sep 11th, 2020
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.36 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define nmax 50005
  3.  
  4. using namespace std;
  5.  
  6. ifstream fin ("dijkstra.in");
  7. ofstream fout ("dijkstra.out");
  8.  
  9. int n, m, x, y, C, D[nmax];
  10. bool viz[nmax];
  11. vector < pair < int , int > > G[nmax];
  12. const int inf = (1 << 30);
  13.  
  14. struct fcmp {
  15.     bool operator () (int x, int y) {
  16.         return D[x] > D[y];
  17.     }
  18. };
  19.  
  20. priority_queue < int, vector < int >, fcmp > Q;
  21.  
  22. void Read () {
  23.     fin >> n >> m;
  24.     while (m --) {
  25.         fin >> x >> y >> C;
  26.         G[x].push_back ({y, C});
  27.     }
  28. }
  29.  
  30. void Dijkstra (int start) {
  31.     for (int i = 1; i <= n; ++i) D[i] = inf;
  32.     D[start] = 0;
  33.     Q.push (start);
  34.     viz[start] = true;
  35.     while (!Q.empty()) {
  36.         int nod = Q.top();
  37.         Q.pop();
  38.         viz[nod] = false;
  39.         for (size_t i = 0; i < G[nod].size(); ++i) {
  40.             int vecin = G[nod][i].first;
  41.             int cost = G[nod][i].second;
  42.             if (D[nod] + cost < D[vecin]) {
  43.                 D[vecin] = D[nod] + cost;
  44.                 if (!viz[vecin]) {
  45.                     Q.push (vecin);
  46.                     viz[vecin] = true;
  47.                 }
  48.             }
  49.         }
  50.     }
  51. }
  52.  
  53. void Print () {
  54.     for (int i = 2; i <= n; ++i) if (D[i] != inf) fout << D[i] << " ";
  55.                                     else fout << "0 ";
  56. }
  57.  
  58. int main() {
  59.     Read ();
  60.     Dijkstra (1);
  61.     Print ();
  62.     return 0;
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment