-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathLCA v2.cpp
51 lines (44 loc) · 897 Bytes
/
LCA v2.cpp
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
# include <fstream>
# include <algorithm>
# include <vector>
# define NR 100005
# define H 200
using namespace std;
ifstream f("lca.in");
ofstream g("lca.out");
vector <int> v[NR];
int i,j,n,m,k,L,VV,Q,x,y;
int poz[NR], niv[NR], T[NR], T2[NR];
void DFS (int k, int nivel, int tata)
{
T2[k]=tata; niv[k]=nivel;
if (nivel%H==0) tata=k;
for (int i=0; i<v[k].size(); ++i)
DFS (v[k][i], nivel+1, tata);
}
int main ()
{
f>>n>>Q;
for (i=2; i<=n; ++i)
{
f>>x; T[i]=x;
v[x].push_back(i);
}
DFS (1, 0, 0);
for (i=1; i<=Q; ++i)
{
f>>x>>y;
while (T2[x]!=T2[y])
{
if (niv[x]<niv[y]) y=T2[y];
else x=T2[x];
}
while (x!=y)
{
if (niv[x]<niv[y]) y=T[y];
else x=T[x];
}
g<<x<<"\n";
}
return 0;
}