Advertisement
Josif_tepe

Untitled

Nov 2nd, 2023
953
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.73 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. int depth[maxn];
  16. void dfs(int node, int parent, int dist) {
  17.     timer++;
  18.     in_dfs[node] = timer;
  19.     up_node[node][0] = parent;
  20.     depth[node] = dist;
  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, dist + 1);
  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 a, b;
  60.         cin >> a >> b;
  61.         graph[a].push_back(b);
  62.         graph[b].push_back(a);
  63.     }
  64.     dfs(1, 1, 0);
  65.    
  66.  
  67.     for(int i = 0; i < q; i++) {
  68.         int a, b;
  69.         cin >> a >> b;
  70.         int res = depth[a] + depth[b] - 2 * depth[LCA(a, b)];
  71.         cout << res << endl;
  72.     }
  73.    
  74.     return 0;
  75. }
  76.  
  77. /*
  78.  12
  79.  1 2
  80.  2 4
  81.  2 5
  82.  4 7
  83.  5 8
  84.  1 3
  85.  3 6
  86.  6 9
  87.  6 10
  88.  6 11
  89.  11 12
  90.  
  91.  **/
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement