Advertisement
LA77

Untitled

Feb 25th, 2025
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. /// INPUT / OUTPUT
  5. const string problem = "lca";
  6. ifstream fin(problem + ".in");
  7. ofstream fout(problem + ".out");
  8.  
  9. /// GLOBAL VARIABLES
  10. const int NMAX = 1e5 + 5, LOG = 25;
  11. int n, m, k;
  12. int g[NMAX], depth[2*NMAX], euler[2*NMAX], poz[2*NMAX];
  13. int rmq[LOG][2 * NMAX];
  14. vector<int>graph[NMAX];
  15.  
  16. inline void DFS(int curr_node, int h)
  17. {
  18. euler[++k] = curr_node;
  19. depth[k] = h;
  20. poz[curr_node] = k;
  21.  
  22. for(auto new_node : graph[curr_node])
  23. {
  24. DFS(new_node, h + 1);
  25. euler[++k] = curr_node;
  26. depth[k] = h;
  27. }
  28. }
  29.  
  30. inline void RMQ()
  31. {
  32. for(int i = 1; i <= k; ++ i)
  33. rmq[0][i] = i;
  34.  
  35. for(int i = 1; (1 << i) <= k; ++ i)
  36. {
  37. for(int j = 1; j <= k; ++ j)
  38. {
  39. if(depth[rmq[i-1][j]] < depth[rmq[i-1][j + (1 << (i - 1))]])
  40. rmq[i][j] = rmq[i-1][j];
  41. else
  42. rmq[i][j] = rmq[i-1][j + (1 << (i - 1))];
  43. }
  44. }
  45. }
  46.  
  47. int main()
  48. {
  49. ios::sync_with_stdio(false);
  50. fin.tie(NULL);
  51. fout.tie(NULL);
  52.  
  53. fin >> n >> m;
  54.  
  55. for(int i = 2; i <= n; ++ i)
  56. {
  57. fin >> g[i];
  58. graph[g[i]].push_back(i);
  59. }
  60.  
  61. DFS(1, 0);
  62. RMQ();
  63.  
  64. while(m--)
  65. {
  66. int a, b;
  67. fin >> a >> b;
  68.  
  69. a = poz[a];
  70. b = poz[b];
  71. if(a > b)
  72. swap(a, b);
  73.  
  74. int k = log2(b - a + 1);
  75.  
  76. if(depth[rmq[k][a]] < depth[rmq[k][b - (1 << k) + 1]])
  77. fout << euler[rmq[k][a]] << '\n';
  78. else
  79. fout << euler[rmq[k][b - (1 << k) + 1]] << '\n';
  80. }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement