-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsloth naptime.cpp
105 lines (91 loc) · 1.53 KB
/
sloth naptime.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
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
99
100
101
102
103
104
105
#include<iostream>
#include<vector>
#include<bits/stdc++.h>
#define lli long long int
#define mod 1000000007
#define pb push_back
#define mk make_pair
#define fastio ios_base::sync_with_stdio(false); cout.tie(NULL);
using namespace std;
vector<int> ar[300001];
int lca[300001][23],dist[300001],maxN;
void DFS(int src,int par,int d)
{
dist[src]=d;
lca[src][0]=par;
for(auto child : ar[src])
if(child!=par)
DFS(child,src,d+1);
}
int findLCA(int src,int dest)
{
if(dist[src]>dist[dest])
swap(src,dest);
int i,d=dist[dest]-dist[src];
while(d)
{
i=log2(d);
dest=lca[dest][i];
d-=(1<<i);
}
if(src==dest)
return src;
for(i=maxN;i>=0;i--)
{
if(lca[src][i]!=-1 && (lca[src][i]!=lca[dest][i]))
{
src=lca[src][i];
dest=lca[dest][i];
}
}
return lca[src][0];
}
int findNthParent(int src,int n)
{
int i;
while(n)
{
i=log2(n);
src=lca[src][i];
n-=(1<<i);
}
return src;
}
int main()
{
fastio;
int n,q,a,b,i,j,c,distance,LCA,dist_LCA;
cin>>n;
maxN=log2(n)+1;
for(i=0;i<n-1;i++)
cin>>a>>b , ar[a].pb(b), ar[b].pb(a);
for(j=0;j<=maxN;j++)
for(i=1;i<=n;i++)
lca[i][j]=-1;
DFS(1,-1,0);
for(j=1;j<=maxN;j++)
{
for(i=1;i<=n;i++)
{
if(lca[i][j-1]!=-1)
{
LCA=lca[i][j-1];
lca[i][j]=lca[LCA][j-1];
}
}
}
cin>>q;
while(q--)
{
cin>>a>>b>>c;
LCA=findLCA(a,b);
distance=dist[a]+dist[b]-2*dist[LCA];
if(distance<=c)
cout<<b<<"\n";
else if(c<=(dist[a]-dist[LCA]))
cout<<findNthParent(a,c)<<"\n";
else
cout<<findNthParent(b,distance-c)<<"\n";
}
return 0;
}