-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathK'th parent of a node.cpp
105 lines (89 loc) · 1.34 KB
/
K'th parent of a node.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
// k'th parent of node in a TREE
//AnkitCode99 here....
//every ups and downs matter!
#include<bits/stdc++.h>
#define endl "\n"
#define Ryuga ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr)
typedef long long int ll;
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define pb push_back
using namespace std;
const ll sz=1e5+5;
const ll szz=1e6+6;
const ll mod=1e9+7;
vector<ll> ar[sz];
ll kpar[sz][20];
void dfs(ll node,ll par)
{
kpar[node][0]=par;
rep(i,1,20)
{
ll temp=kpar[node][i-1];
kpar[node][i]=kpar[temp][i-1];
}
for(ll x:ar[node])
{
if(x!=par)
{
dfs(x,node);
}
}
}
int main()
{
Ryuga;
#ifndef ONLINE_JUDGE
freopen("IP.txt","r",stdin);
freopen("OP.txt","w",stdout);
#endif
clock_t startTime=clock();
ll n;
cin>>n;
rep(i,0,n-1)
{
ll a,b;
cin>>a>>b;
ar[a].pb(b);
ar[b].pb(a);
}
dfs(1,-1);
ll q;
cin>>q;
while(q--)
{
ll node,k_th;
cin>>node>>k_th;
ll cnt=0;
while(k_th)
{
if(k_th & 1)
{
node=kpar[node][cnt];
}
k_th>>=1;
cnt++;
}
cout<<node<<endl;
}
cerr << endl <<setprecision(20)<< double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
}//Goodbye...
/*
Test Case
14
1 2
1 3
3 5
2 4
4 6
4 7
6 8
8 11
8 12
12 14
7 9
7 10
9 13
2
11 2
7 3
*/