Advertisement
MathQ_

Untitled

Mar 16th, 2021
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1. int n;
  2. const int LOG = 20;
  3. int timer = 0;
  4. vector<vector<int>> g;
  5. vector<vector<int>> up;
  6. vector<int> depth;
  7. vector<int> tin, tout;
  8.  
  9. void resize_all(int n) {
  10.     g.resize(n);
  11.     up.resize(n, vector<int> (LOG));
  12.     depth.resize(n);
  13.     tin.resize(n);
  14.     tout.resize(n);
  15. }
  16.  
  17. void clear_all() {
  18.     g.clear();
  19.     up.clear();
  20.     depth.clear();
  21.     tin.clear();
  22.     tout.clear();
  23. }
  24.  
  25. void dfs(int v, int p = 0) {
  26.     tin[v] = timer++;
  27.     up[v][0] = p;
  28.     for (int i = 1; i < LOG; ++i) {
  29.         up[v][i] = up[up[v][i - 1]][i - 1];
  30.     }
  31.     for (auto u : g[v]) {
  32.         if (u != p) {
  33.             depth[u] = depth[v] + 1;
  34.             dfs(u, v);
  35.         }
  36.     }
  37.     tout[v] = timer++;
  38. }
  39.  
  40. bool isAncestor(int v, int u) {
  41.     return tin[v] <= tin[u] && tout[u] <= tout[v];
  42. }
  43.  
  44. int Max(int v, int u) {
  45.     return (depth[v] > depth[u] ? v : u);
  46. }
  47.  
  48. int lca(int v, int u) {
  49.     if (isAncestor(v, u)) return v;
  50.     if (isAncestor(u, v)) return u;
  51.     for (int i = LOG - 1; i >= 0; --i) {
  52.         if (!isAncestor(up[v][i], u)) {
  53.             v = up[v][i];
  54.         }
  55.     }
  56.     return up[v][0];
  57. }
  58.  
  59. void solve() {
  60.     clear_all();
  61.     resize_all(n);
  62.     int v, u;
  63.     timer = 0;
  64.     int root = 0;
  65.     for (int i = 0; i < n - 1; ++i) {
  66.         cin >> v >> u;
  67.         --v; --u;
  68.         g[v].push_back(u);
  69.         g[u].push_back(v);
  70.     }
  71.  
  72.     dfs(root);
  73.     int q;
  74.     cin >> q;
  75.     char type;
  76.     while (q--) {
  77.         cin >> type;
  78.         if (type == '?') {
  79.             cin >> v >> u;
  80.             --v; --u;
  81.             int lca1 = lca(v, u);
  82.             int lca2 = lca(v, root);
  83.             int lca3 = lca(u, root);
  84.  
  85.             cout << Max(Max(lca1, lca2), lca3) + 1 << "\n";
  86.         } else {
  87.             cin >> root;
  88.             --root;
  89.         }
  90.     }
  91.     int useless;
  92.     cin >> useless;
  93. }
  94.  
  95. int main() {
  96.     fast
  97.     // file_in
  98.     // file_in_out
  99.    
  100.     while (cin >> n) {
  101.         solve();
  102.     }
  103.     return 0;
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement