Advertisement
Guest User

Untitled

a guest
May 22nd, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MAXN 100005
  3. using namespace std;
  4. ifstream in("lca.in");
  5. ofstream out("lca.out");
  6. int n, m, parent[MAXN], lev[MAXN], v[MAXN], h, r;
  7. int t_bloc[MAXN];
  8.  
  9. vector<int> fii[MAXN];
  10.  
  11.  
  12. void h_dfs(int nod, int level) {
  13. v[nod] = 1;
  14. lev[nod] = level;
  15. if(level > h) {
  16. h = level;
  17. }
  18. for(int i : fii[nod]) {
  19. if(v[i] == 0) {
  20. h_dfs(i, level + 1);
  21. }
  22. }
  23. }
  24.  
  25. void dfs(int nod, int t_b) {
  26. t_bloc[nod] = t_b;
  27. if(lev[nod] % r == 0) {
  28. t_b = nod;
  29. }
  30. for(int i : fii[nod]) {
  31. dfs(i, t_b);
  32. }
  33. }
  34.  
  35. int lca(int x, int y) {
  36. while(t_bloc[x] != t_bloc[y]) {
  37. if(lev[x] > lev[y]) {
  38. x = t_bloc[x];
  39. } else {
  40. y = t_bloc[y];
  41. }
  42. }
  43. while(x != y) {
  44. if(lev[x] > lev[y]) {
  45. x = parent[x];
  46. } else {
  47. y = parent[y];
  48. }
  49. }
  50. return x;
  51. }
  52.  
  53. int main() {
  54. in >> n >> m;
  55. for(int i = 1; i < n; ++i) {
  56. int t;
  57. in >> t;
  58. parent[i + 1] = t;
  59. fii[t].push_back(i + 1);
  60. }
  61.  
  62. // Find h
  63. h_dfs(1, 1);
  64. r = sqrt(h);
  65.  
  66. // Calc tatii blocurilor
  67. dfs(1, 1);
  68.  
  69. while(m--) {
  70. int a, b;
  71. in >> a >> b;
  72. out << lca(a, b) << "\n";
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement