Advertisement
MathQ_

Untitled

Mar 15th, 2021
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. const int LOG = 20;
  2. int timer = 1;
  3. vector<vector<int>> g;
  4. vector<vector<int>> up;
  5. vector<int> tin, tout;
  6.  
  7. void resize_all(int n) {
  8.     g.resize(n);
  9.     up.resize(n, vector<int>(LOG, 0));
  10.     tin.resize(n);
  11.     tout.resize(n);
  12. }
  13.  
  14. void dfs(int v, int p) {
  15.     tin[v] = timer++;
  16.     up[v][0] = p;
  17.     for (int i = 1; i < LOG; ++i) {
  18.         up[v][i] = up[up[v][i - 1]][i - 1];
  19.     }
  20.     for (auto u : g[v]) {
  21.         if (u != p) {
  22.             dfs(u, v);
  23.         }
  24.     }
  25.     tout[v] = timer++;
  26. }
  27.  
  28. bool isAncestor(int v, int u) {
  29.     return tin[v] <= tin[u] && tout[u] <= tout[v];
  30. }
  31.  
  32. int lca(int v, int u) {
  33.     if (isAncestor(v, u)) return v;
  34.     if (isAncestor(u, v)) return u;
  35.     for (int i = LOG - 1; i >= 0; --i) {
  36.         if (!isAncestor(up[v][i], u)) {
  37.             v = up[v][i];
  38.         }
  39.     }
  40.     return up[v][0];
  41. }
  42.  
  43. int main() {
  44.     int n;
  45.     cin >> n;
  46.     resize_all(n);
  47.     int v, u;
  48.     for (int i = 0; i < n - 1; ++i) {
  49.         cin >> v >> u;
  50.         --v; --u;
  51.         g[v].push_back(u);
  52.         g[u].push_back(v);
  53.     }
  54.     dfs(0, 0);
  55.     timer = 1;
  56.     int q;
  57.     cin >> q;
  58.     char type;
  59.     while (q--) {
  60.         cin >> type;
  61.         if (type == '?') {
  62.             cin >> v >> u;
  63.             --v; --u;
  64.             cout << lca(v, u) + 1 << '\n';
  65.         } else {
  66.             cin >> v;
  67.             --v;
  68.             dfs(v, v);
  69.             timer = 1;
  70.         }
  71.     }
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement