Advertisement
Josif_tepe

Untitled

Nov 2nd, 2023
802
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. #include <fstream>
  5. #include <cstring>
  6. using namespace std;
  7. const int maxn = 2e5 + 10;
  8. const int logn = 24;
  9. int n;
  10. vector<int> graph[maxn];
  11. int timer = 0;
  12. int in_dfs[maxn], out_dfs[maxn];
  13. int parent[maxn];
  14. int up_node[maxn][logn];
  15.  
  16. void dfs(int node, int parent) {
  17.     timer++;
  18.     in_dfs[node] = timer;
  19.     up_node[node][0] = parent;
  20.    
  21.     for(int i = 1; i < logn; i++) {
  22.         up_node[node][i] = up_node[up_node[node][i - 1]][i - 1];
  23.     }
  24.     for(int neighbour : graph[node]) {
  25.         if(neighbour != parent) {
  26.             dfs(neighbour, node);
  27.         }
  28.     }
  29.     timer++;
  30.     out_dfs[node] = timer;
  31.    
  32. }
  33. bool is_ancestor(int A, int B) {
  34.     if(in_dfs[A] <= in_dfs[B] and out_dfs[A] >= out_dfs[B]) {
  35.         return true;
  36.     }
  37.     return false;
  38. }
  39. int LCA(int A, int B) {
  40.     if(is_ancestor(A, B)) {
  41.         return A;
  42.     }
  43.     if(is_ancestor(B, A)) {
  44.         return B;
  45.     }
  46.     for(int i = logn - 1; i >= 0; i--) {
  47.         if(!is_ancestor(up_node[A][i], B)) {
  48.             A = up_node[A][i];
  49.         }
  50.     }
  51. //    cout << A << endl;
  52.     return up_node[A][0];
  53. }
  54. int main() {
  55.     int q;
  56.     cin >> n >> q;
  57.     parent[1] = 0;
  58.     for(int i = 2; i <= n; i++) {
  59.         int p;
  60.         cin >> p;
  61.        
  62.         graph[i].push_back(p);
  63.         graph[p].push_back(i);
  64.         parent[i] = p;
  65.     }
  66.     dfs(1, 1);
  67.    
  68.  
  69.     for(int i = 0; i < q; i++) {
  70.         int a, b;
  71.         cin >> a >> b;
  72.         cout << LCA(a, b) << endl;
  73.     }
  74.    
  75.     return 0;
  76. }
  77.  
  78. /*
  79.  12
  80.  1 2
  81.  2 4
  82.  2 5
  83.  4 7
  84.  5 8
  85.  1 3
  86.  3 6
  87.  6 9
  88.  6 10
  89.  6 11
  90.  11 12
  91.  
  92.  **/
  93.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement