DuongNhi99

PWALK

Jan 12th, 2022
877
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. using ll = long long;
  5. using pii = pair<ll, int>;
  6. using tpii = tuple<int, int, int>;
  7.  
  8. const int maxN = 1e5 + 5;
  9. const ll INF = 1e18 + 7;
  10. const int MOD = 1e9 + 7;
  11.  
  12. int n, nTest;
  13. vector<pii> graph[maxN];
  14.  
  15. ll d[maxN];
  16.  
  17. void Dijkstra(int s, int t) {
  18.     fill(d + 1, d + n + 1, INF);
  19.     d[s] = 0;
  20.     priority_queue<pii, vector<pii>, greater<pii>> pq;
  21.     pq.push({0, s});
  22.  
  23.     while (!pq.empty()) {
  24.         const auto [du, u] = pq.top(); pq.pop();
  25.  
  26.         if (d[u] > du) continue;
  27.  
  28.         for (const auto &[uv, v] : graph[u]) {
  29.             if (d[v] > d[u] + uv) {
  30.                 d[v] = d[u] + uv;
  31.                 pq.push({d[v], v});
  32.             }
  33.         }
  34.     }
  35. }
  36.  
  37. int main() {
  38. #ifdef LOCAL
  39.     freopen("in1.txt", "r", stdin);
  40. #else
  41.     freopen("PWALK.inp", "r", stdin);
  42.     freopen("PWALK.out", "w", stdout);
  43. #endif
  44.     ios_base::sync_with_stdio(false);
  45.     cin.tie(nullptr);
  46.  
  47.     cin >> n >> nTest;
  48.     for (int i = 1; i <= n-1; i++) {
  49.         int u, v, w; cin >> u >> v >> w;
  50.         graph[u].push_back({w, v});
  51.         graph[v].push_back({w, u});
  52.     }
  53.  
  54.     for (int i = 1; i <= nTest; ++i) {
  55.         int u, v; cin >> u >> v;
  56.         Dijkstra(u, v);
  57.         cout << d[v] << '\n';
  58.     }
  59.  
  60.     return 0;
  61. }
  62.  
Advertisement
Add Comment
Please, Sign In to add comment