bhupixb

LCA binary lifting

Jul 10th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. // #include "bits/stdc++.h"
  2. #include "iostream"
  3. #include "vector"
  4. #include "map"
  5. using namespace std;
  6. #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL);
  7.  
  8. const int N = 1e5 + 6;
  9.  
  10. class LCA {
  11. vector < int > g[N];
  12. int up[N][18], in[N];
  13. int t = 0, out[N], n;
  14. public:
  15. LCA() {
  16. for (int i = 0; i < N; ++i) {
  17. in[i] = out[i] = 0;
  18. }
  19. }
  20. void dfs(int u, int p) {
  21. in[u] = ++t;
  22. up[u][0] = p;
  23. for (int i = 1; i < 18; ++i) {
  24. up[u][i] = up[up[u][i-1]][i-1];
  25. // f(u, i) = f(f(u, i-1), i-1); (Recurrence Relation)
  26. }
  27. for (auto i : g[u]) {
  28. if (i != p) {
  29. dfs(i, u);
  30. }
  31. }
  32. out[u] = ++t;
  33. }
  34. // Check if u is ancestor of v or not
  35. inline bool ancestor(int u, int v) {
  36. return (in[u] <= in[v] && out[u] >= out[v]);
  37. }
  38. inline int lca(int u, int v) {
  39. if (ancestor(u, v)) {
  40. return u; // If u is ancestor of v
  41. } else if(ancestor(v, u)) {
  42. return v; // If v is ancestor of u
  43. } else {
  44. for (int i = 17; i >= 0; --i) {
  45. if (!ancestor(up[u][i], v)) {
  46. u = up[u][i];
  47. }
  48. }
  49. }
  50. return up[u][0];
  51. }
  52. void inp() {
  53. int l, r;
  54. cin >> n;
  55. for (int i = 1; i < n; ++i) {
  56. cin >> l >> r;
  57. g[l].push_back(r);
  58. g[r].push_back(l);
  59. }
  60. dfs(1, 1);
  61. }
  62.  
  63. };
  64.  
  65. signed main() {
  66. fast;
  67. LCA G;
  68. G.inp();
  69. return 0;
  70. }
Add Comment
Please, Sign In to add comment