-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlca.cpp
More file actions
91 lines (90 loc) · 1.77 KB
/
lca.cpp
File metadata and controls
91 lines (90 loc) · 1.77 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
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+5,LN=25;
typedef long long ll;
int st[N][LN];
int pa[N],h[N],n;
ll dist[N];
vector<int> adj[N],adjw[N];
void dfs(int u)
{
for (int i=0; i<adj[u].size(); i++)
{
int v=adj[u][i];
int w=adjw[u][i];
if(v==pa[u])
continue;
if(h[v]==-1)
{
dist[v]=dist[u]+w;
h[v]=h[u]+1;
pa[v]=u;
dfs(v);
}
}
}
void build_st()
{
memset(st,-1,sizeof st);
for (int i=1; i<=n; i++)
st[i][0]=pa[i];
for (int j=1; j<LN; j++)
{
for (int i=0; i<n; i++)
{
st[i][j]=st[st[i][j-1]][j-1];
}
}
}
int LCA(int u,int v)
{
if(h[u]<h[v])
swap(u,v);
for (int i=LN-1; i>=0; i--)
{
if(h[u]-h[v]>=(1<<i))
u=st[u][i];
}
if(u==v)
return u;
for (int i=LN-1; i>=0; i--)
{
if(st[u][i]!=-1 && st[u][i]!=st[v][i])
{
u=st[u][i];
v=st[v][i];
}
}
return st[u][0];
}
int main()
{
while(scanf("%d", &n) && n!=0)
{
memset(h,-1,sizeof h);
memset(pa,-1,sizeof pa);
for (int i=0; i<n; i++)
adj[i].clear(),adjw[i].clear();
for (int i=1; i<n; i++)
{
int a,l;
scanf("%d %d", &a, &l);
adj[a].push_back(i);
adj[i].push_back(a);
adjw[a].push_back(l);
adjw[i].push_back(l);
}
dfs(0);
build_st();
int q;
scanf("%d", &q);
for (int i=1; i<=q; i++)
{
int s,t;
scanf("%d %d", &s, &t);
printf("%lld ",dist[s]+dist[t]-2*dist[LCA(s,t)]);
}
printf("\n");
}
return 0;
}