DuongNhi99

CJDICHUYENLUCLUONG (lqdoj) - Dijkstra*

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