Advertisement
Vince14

/<> 11437 (basic LCA)

Sep 29th, 2023
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.04 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <cstring>
  4. #include <algorithm>
  5. #include <cmath>
  6. #include <vector>
  7. #include <set>
  8. #include <map>
  9. #include <stack>
  10. #include <queue>
  11. #include <deque>
  12. #include <unordered_map>
  13. #include <numeric>
  14. #include <iomanip>
  15. using namespace std;
  16. #define pii pair<long long, long long>
  17. #define ll long long
  18. #define FAST ios_base::sync_with_stdio(false); cin.tie(NULL)
  19. const long long dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};
  20. const long long dl[2] = {1, -1};
  21. const long long MOD = 1000000007;
  22. const long long MAXN = 50005;
  23.  
  24. int N, M;
  25. vector<int> adj[MAXN];
  26. int par[MAXN][22];
  27. int depth[MAXN];
  28.  
  29.  
  30. void make_tree(int c, int p, int d){
  31.     depth[c] = d;
  32.     par[c][0] = p;
  33.     for(auto x : adj[c]){
  34.         if(x != p){
  35.             make_tree(x, c, d + 1);
  36.         }
  37.     }
  38. }
  39.  
  40.  
  41. int main() {
  42.     FAST;
  43.     cin >> N;
  44.     for(int x, y, i = 0; i < N - 1; i++){
  45.         cin >> x >> y;
  46.         adj[x].push_back(y);
  47.         adj[y].push_back(x);
  48.     }
  49.     make_tree(1, 0, 0);
  50.     for(int j = 1; j <= 20; j++){
  51.         for(int i = 2; i <= N; i++){
  52.             par[i][j] = par[par[i][j - 1]][j - 1];
  53.         }
  54.     }
  55.     cin >> M;
  56.     for(int x, y, i = 0; i < M; i++){
  57.         cin >> x >> y;
  58.         if(depth[x] < depth[y]){
  59.             swap(x, y);
  60.         }
  61.         if(depth[x] != depth[y]){
  62.             int tmp = depth[x] - depth[y];
  63.             for(int j = 0; j <= 20; j++){
  64.                 if((tmp & (1 << j)) != 0){
  65.                     x = par[x][j];
  66.                 }
  67.             }
  68.         }
  69.         // depth[x] = depth[y]
  70.         if(x == y){
  71.             cout << y << "\n";
  72.             continue;
  73.         }
  74.         for(int j = 20; j >= 0; j--){
  75.             int xx = par[x][j];
  76.             int yy = par[y][j];
  77.             if(xx != yy){
  78.                 x = xx;
  79.                 y = yy;
  80.             }
  81.         }
  82.         cout << par[x][0] << "\n";
  83.     }
  84. }
  85.  
  86. /*
  87. 15
  88. 1 2
  89. 1 3
  90. 2 4
  91. 3 7
  92. 6 2
  93. 3 8
  94. 4 9
  95. 2 5
  96. 5 11
  97. 7 13
  98. 10 4
  99. 11 15
  100. 12 5
  101. 14 7
  102. 6
  103. 6 11
  104. 10 9
  105. 2 6
  106. 7 6
  107. 8 13
  108. 8 15
  109.  */
  110.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement