-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCA2.cpp
More file actions
98 lines (83 loc) · 2.09 KB
/
LCA2.cpp
File metadata and controls
98 lines (83 loc) · 2.09 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cstdio>
using namespace std;
vector<int> tree[100001];
bool isChecked[100001];
int depth[100001];
int parent[100001];
int memoiztion[100001][500];
int lca(int u, int v) {
if (depth[u] < depth[v]) {
swap(u,v);
}
int log = 1;
for (log=1; (1<<log) <= depth[u]; log++);
log-=1;
for (int i=log; i>=0; i--) {
if (depth[u] - (1<<i) >= depth[v]) {
u = memoiztion[u][i];
}
}
if (u == v) {
return u;
} else {
for (int i=log; i>=0; i--) {
if (memoiztion[u][i] != 0 && memoiztion[u][i] != memoiztion[v][i]) {
u = memoiztion[u][i];
v = memoiztion[v][i];
}
}
return parent[u];
}
}
int main()
{
int nodeNum;
scanf("%d", &nodeNum);
// cin >> nodeNum;
for(int i = 0; i < nodeNum - 1; i++) {
int start, end;
scanf("%d %d", &start, &end);
// cin >> start >> end;
tree[start].push_back(end);
tree[end].push_back(start);
}
depth[1] = 0;
queue<int> q;
q.push(1);
while(!q.empty()) {
int current = q.front();
q.pop();
isChecked[current] = true;
for(int i = 0, len = tree[current].size(); i < len; i++) {
int child = tree[current][i];
if(!isChecked[child]) {
depth[child] = depth[current] + 1;
parent[child] = current;
q.push(child);
}
}
}
for (int i=1; i<=nodeNum; i++) {
memoiztion[i][0] = parent[i];
}
for(int j = 1; (1<<j) < nodeNum; j++) {
for(int i = 1; i <= nodeNum; i++) {
if(memoiztion[i][j - 1] != 0 ) {
memoiztion[i][j] = memoiztion[memoiztion[i][j - 1]][j - 1];
}
}
}
int problemNum;
// cin >> problemNum;
scanf("%d", &problemNum);
while(problemNum--) {
int node1, node2;
scanf("%d %d",&node1, &node2);
printf("%d\n",lca(node1, node2));
}
return 0;
}