-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathLCA using 2 pointers.cpp
More file actions
68 lines (51 loc) · 985 Bytes
/
LCA using 2 pointers.cpp
File metadata and controls
68 lines (51 loc) · 985 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5;
vector<int> gr[N];
int dep[N], Par[N];
void dfs(int cur, int par) {
Par[cur] = par;
dep[cur] = dep[par] + 1;
for (auto x : gr[cur]) {
if (x != par) {
dfs(x, cur);
}
}
}
int LCA(int u, int v) {
if (u == v) return u;
if (dep[u] < dep[v]) swap(u, v);
// depth of u is more than depth of v
int diff = dep[u] - dep[v];
// depth of both nodes same
while (diff--) {
u = Par[u];
}
// until they are equal nodes keep climbing
while (u != v) {
u = Par[u];
v = Par[v];
}
return u;
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n;
cin >> n;
for (int i = 1; i < n; i++) {
int x, y;
cin >> x >> y;
gr[x].push_back(y);
gr[y].push_back(x);
}
dfs(1, 0);
// for (int i = 1; i <= n; i++) {
// cout << i << " " << dep[i] << '\n';
// }
cout << LCA(9, 12) << '\n';
cout << LCA(10, 8) << '\n';
cout << LCA(9, 11) << '\n';
return 0;
}