DuongNhi99

CJDUTIEC (lqdoj) - Dijkstra

Mar 30th, 2021 (edited)
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. // https://lqdoj.edu.vn/problem/CJDUTIEC
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. using ll = long long;
  6. using pi32 = pair<int, int>;
  7. using pi64 = pair<int64_t, int64_t>;
  8. using ti32 = tuple<int, int, int>;
  9. using ti64 = tuple<int64_t, int64_t, int64_t>;
  10.  
  11. const int N = 1e5 + 5;
  12. const int INF = 1e18 + 7;
  13.  
  14. int n, nE, s, t;
  15. vector<pi32> graph[N];
  16.  
  17. int64_t d[N];
  18. int parent[N];
  19.  
  20. void Dijkstra(int s) {
  21.     fill(parent + 1, parent + n + 1, -1);
  22.     fill(d + 1, d + n + 1, INF);
  23.     d[s] = 0;
  24.     priority_queue<pi64, vector<pi64>, greater<pi64>> pq;
  25.     pq.push({0, s});
  26.  
  27.     while (!pq.empty()) {
  28.         const auto [du, u] = pq.top(); pq.pop();
  29.  
  30.         if (d[u] > du) continue;
  31.  
  32.         for (const auto &[uv, v] : graph[u]) {
  33.             if (d[v] > d[u] + uv) {
  34.                 d[v] = d[u] + uv;
  35.                 parent[v] = u;
  36.                 pq.push({d[v], v});
  37.             }
  38.         }
  39.     }
  40. }
  41.  
  42. int main() {
  43. #ifdef LOCAL
  44.     freopen("in.txt", "r", stdin);
  45. #else
  46.     freopen("CJDUTIEC.inp", "r", stdin);
  47.     freopen("CJDUTIEC.out", "w", stdout);
  48. #endif
  49.     ios_base::sync_with_stdio(false);
  50.     cin.tie(nullptr);
  51.  
  52.     cin >> n >> nE >> s >> t;
  53.  
  54.     for (int i = 1; i <= nE; i++) {
  55.         int u, v, w; cin >> u >> v >> w;
  56.         graph[u].push_back({w, v});
  57.         graph[v].push_back({w, u});
  58.     }
  59.  
  60.     Dijkstra(s);
  61.  
  62.     vector<int> path;
  63.     int u = t;
  64.     while (u != -1) {
  65.         path.push_back(u);
  66.         u = parent[u];
  67.     }
  68.  
  69.     cout << d[t] << '\n';
  70.     reverse(path.begin(), path.end());
  71.     for (int u : path)
  72.         cout << u << ' ';
  73.  
  74.     return 0;
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment