Advertisement
cosenza987

123321312

Sep 1st, 2022
804
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. //Слава Україні, Героям слава
  2.  
  3. #include <bits/stdc++.h>
  4.  
  5. using namespace std;
  6.  
  7. int t, n, l, q;
  8. vector<vector<pair<int, int>>> adj;
  9. vector<vector<int>> up, ans;
  10. vector<int> tin, tout, h;
  11.  
  12. void dfs(int v, int w = INT_MAX, int p = 1, int hh = 0) {
  13.     tin[v] = ++t;
  14.     up[v][0] = p;
  15.     ans[v][0] = w;
  16.     for (int i = 1; i <= l; i++) {
  17.         up[v][i] = up[up[v][i - 1]][i - 1];
  18.         ans[v][i] = min(ans[v][i - 1], ans[up[v][i - 1]][i - 1]);
  19.     }
  20.     for (auto u : adj[v]) {
  21.         if (u.first != p) {
  22.             dfs(u.first, u.second, v, hh + 1);
  23.         }
  24.     }
  25.     h[v] = hh;
  26.     tout[v] = ++t;
  27. }
  28.  
  29. bool isanc(int u, int v) {
  30.     return tin[u] <= tin[v] and tout[u] >= tout[v];
  31. }
  32.  
  33. int lca(int u, int v) {
  34.     if (isanc(u, v)) {
  35.         return u;
  36.     }
  37.     if (isanc(v, u)) {
  38.         return v;
  39.     }
  40.     for (int i = l; i >= 0; i--) {
  41.         if (!isanc(up[u][i], v)) {
  42.             u = up[u][i];
  43.         }
  44.     }
  45.     return up[u][0];
  46. }
  47.  
  48. int dist(int u, int v) {
  49.     int k = lca(u, v);
  50.     return abs(h[u] - h[k]) + abs(h[v] - h[k]);
  51. }
  52.  
  53. int calc(int a, int b) {
  54.     int k = lca(a, b);
  55.     int d1 = h[a] - h[k];
  56.     int d2 = h[b] - h[k];
  57.     int res = INT_MAX;
  58.     int cnt = 0;
  59.     while(d1) {
  60.         if(d1 & 1) {
  61.             res = min(res, ans[a][cnt]);
  62.             a = up[a][cnt];
  63.         }
  64.         d1 >>= 1;
  65.         cnt++;
  66.     }
  67.     cnt = 0;
  68.     while(d2) {
  69.         if(d2 & 1) {
  70.             res = min(res, ans[b][cnt]);
  71.             b = up[b][cnt];
  72.         }
  73.         d2 >>= 1;
  74.         cnt++;
  75.     }
  76.     return res;
  77. }
  78.  
  79. int main() {
  80.     ios_base::sync_with_stdio(false);
  81.     cin.tie(0);
  82.     int m;
  83.     cin >> n >> m;
  84.     l = ceil(log2(n + 1)) + 1;
  85.     tin.resize(n + 1); tout.resize(n + 1); h.resize(n + 1);
  86.     adj.resize(n + 1); up.assign(n + 1, vector<int>(l + 1)); ans.assign(n + 1, vector<int>(l + 1));
  87.     for(int i = 0; i < m; i++) {
  88.         int a, b, c;
  89.         cin >> a >> b >> c;
  90.         adj[a].push_back({b, c});
  91.         adj[b].push_back({a, c});
  92.     }
  93.     dfs(1);
  94.     cin >> q;
  95.     while(q--) {
  96.         int a, b;
  97.         cin >> a >> b;
  98.         cout << calc(a, b) << "\n";
  99.     }
  100.     return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement