-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCA.cpp
More file actions
73 lines (59 loc) · 1.6 KB
/
LCA.cpp
File metadata and controls
73 lines (59 loc) · 1.6 KB
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
69
70
71
72
73
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> tree[50001];
vector<int> depth(50001 , 0);
vector<int> parent(50001 , 0);
vector<bool> isChecked(50001, false);
int main()
{
int nodeNum, LCAProblemNum;
cin >> nodeNum;
for(int i = 0; i < nodeNum - 1; i++){
int start, end;
cin >> start >> end;
tree[start].push_back(end);
tree[end].push_back(start);
}
queue<int> q;
q.push(1);
while(!q.empty()) {
int current = q.front();
q.pop();
isChecked[current] = true;
for(auto ele : tree[current]){
if(!isChecked[ele]) {
depth[ele] = depth[current] + 1;
parent[ele] = current;
q.push(ele);
}
}
}
cin >> LCAProblemNum;
for(int i = 0; i < LCAProblemNum; i++) {
int node1, node2;
cin >> node1 >> node2;
int node1Depth = depth[node1];
int node2Depth = depth[node2];
while(node1Depth != node2Depth) {
if(node1Depth > node2Depth) {
node1 = parent[node1];
node1Depth = depth[node1];
}else if(node1Depth < node2Depth){
node2 = parent[node2];
node2Depth = depth[node2];
}
}
if(node1 == node2) {
cout << node1 << '\n';
}else {
while(parent[node1] != parent[node2]) {
node1 = parent[node1];
node2 = parent[node2];
}
cout << parent[node1] << '\n';
}
}
return 0;
}