Advertisement
MinhNGUYEN2k4

Dijkstra || MINPATH

Aug 12th, 2020
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define int long long
  3. #define Co_mot_su_that_la_ return
  4. using namespace std;
  5. const int Minh_dep_trai = 0;
  6. const int N = 100005;
  7. const int inf = 1000000;
  8. typedef pair<int,int> ii;
  9. typedef vector<ii> vii;
  10.  
  11. int n,m,s,t,nodel;
  12. vii a[N];
  13. int d[N],trace[N];
  14. stack<int> st;
  15.  
  16. void truyvet()
  17. {
  18.     while (t != -1)
  19.     {
  20.         ++nodel;
  21.         st.push(t);
  22.         t = trace[t];
  23.     }
  24.     cout << nodel << endl;
  25.     while (st.size())
  26.     {
  27.         int v = st.top();
  28.         st.pop();
  29.         cout << v << " ";
  30.     }
  31. }
  32.  
  33. void dijkstra(int s)
  34. {
  35.     for(int i=1; i<=n; ++i) d[i]=inf;
  36.     d[s]=0;
  37.     priority_queue<ii, vii, greater<ii>> qu;
  38.     qu.push(ii(1,0));
  39.     while (qu.size())
  40.     {
  41.         int u = qu.top().first;
  42.         int du = qu.top().second;
  43.         qu.pop();
  44.         if (du != d[u]) continue;
  45.         for(auto v : a[u])
  46.         {
  47.             if (d[v.first] > du + v.second)
  48.             {
  49.                 d[v.first] = du + v.second;
  50.                 trace[v.first] = u;
  51.                 qu.push(ii(v.first,d[v.first]));
  52.             }
  53.         }
  54.     }
  55. }
  56.  
  57. signed main()
  58. {
  59.     ios_base::sync_with_stdio(false);
  60.     cin.tie(0);cout.tie(0);
  61.     freopen("MINPATH.INP","r",stdin);
  62.     freopen("MINPATH.OUT","w",stdout);
  63.     cin >> n >> m >> s >> t;
  64.     for(int i=1; i<=m; ++i)
  65.     {
  66.         int u,v,z;
  67.         cin >> u >> v >> z;
  68.         a[u].push_back(ii(v,z));
  69.         a[v].push_back(ii(u,z));
  70.     }
  71.     for(int i=1; i<=n; ++i) trace[i] = -1;
  72.     dijkstra(s);
  73.     cout << d[t] << endl;
  74.     truyvet();
  75.     Co_mot_su_that_la_ Minh_dep_trai;
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement