Advertisement
Guest User

LCA

a guest
Dec 14th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int n;
  5. vector<int> adj[400009];
  6. int parent[400009], level[400009], anc[400009][20];
  7.  
  8. void dfs(int node, int pr, int l)
  9. {
  10. parent[node] = pr;
  11. level[node] = l;
  12.  
  13. for(auto u : adj[node])
  14. {
  15. if(u != parent[node])
  16. dfs(u, node, l+1);
  17. }
  18. }
  19.  
  20. void lca()
  21. {
  22. dfs(1, -1, 1);
  23.  
  24. int i, j;
  25. for(i = 0; i < n; i++)
  26. {
  27. for(j = 0; (1 << j) < n; j++)
  28. anc[i][j] = 1;
  29. }
  30. for(i = 0; i < n; i++)
  31. anc[i][0] = parent[i];
  32.  
  33. for(j = 1; 1<<j < n; j++)
  34. {
  35. for(i = 0; i < n; i++)
  36. anc[i][j] = anc[anc[i][j-1]][j-1];
  37. }
  38. }
  39.  
  40. int query(int u, int v)
  41. {
  42. if(level[u] < level[v])
  43. swap(u, v);
  44.  
  45. int i;
  46. for(i = log2(n) + 1; i >= 0; i--)
  47. {
  48. if(level[anc[u][i]] >= level[v])
  49. u = anc[u][i];
  50. }
  51.  
  52. for(i = log2(n) + 1; i >= 0; i--)
  53. {
  54. if(anc[u][i] != anc[v][i])
  55. {
  56. u = anc[u][i];
  57. v = anc[v][i];
  58. }
  59. }
  60.  
  61. return parent[u];
  62. }
  63.  
  64.  
  65.  
  66. int main()
  67. {
  68. int i, u, v;
  69. cin >> n;
  70.  
  71. for(i = 0; i < n-1; i++)
  72. {
  73. cin >> u >> v;
  74. adj[u].push_back(v);
  75. adj[v].push_back(u);
  76. }
  77.  
  78. lca();
  79.  
  80. int q;
  81. cin >> q;
  82. while(q--)
  83. {
  84. cin >> u >> v;
  85. cout << query(u, v) << endl;
  86. }
  87. }
  88. /*
  89. 10
  90. 1 3
  91. 1 7
  92. 3 2
  93. 3 10
  94. 2 6
  95. 5 7
  96. 8 5
  97. 5 9
  98. 7 4
  99. 2
  100. 10 6
  101. 2 6
  102. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement