-
Notifications
You must be signed in to change notification settings - Fork 1
/
图论-LCA-在线算法.cpp
122 lines (111 loc) · 1.89 KB
/
图论-LCA-在线算法.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include<bits/stdc++.h>
#define per(i,a,b) for(int i = (a);i <= (b);++i)
#define rep(i,a,b) for(int i = (b);i >= (b);--i)
using namespace std;
const int maxn = 2e5 + 10,maxv = 1e3 + 30;
struct node{
int to,nex,w;
};
node e[maxn];
int head[maxn];
vector<int> g;//记录dfs序列
int first[maxn];//first[i]记录i第一次出现的数组下标
int dp[maxv][maxv];
int n = 0,cntv = 0;
int in[maxn];
void init(){
cntv = 0;
memset(head,-1,sizeof(head)); memset(in,0,sizeof(in)); memset(first,-1,sizeof(first)); memset(dp,0x3f,sizeof(dp));
}
void add_edge(int from,int to,int w){
e[++cntv] = node{to,head[from],w};
head[from] = cntv;
}
void dfs(int s){
g.push_back(s);
//first[s] = (first[s] == -1 ? g.size() : first[s]);
if(first[s] == -1){
first[s] = g.size();
}
for(int i = head[s];i != -1;i = e[i].nex){
dfs(e[i].to);
g.push_back(s);
}
}
void ST(){
int si = g.size();
int k = 0;
while((1 << (k+1)) < si){
++k;
}
per(i,1,si){
dp[i][0] = g[i-1];
}
per(j,1,k){
for(int i = 1;i + (1<<j) <= si;++i){
dp[i][j] = min(dp[i][j-1],dp[i+(1<<(j-1))][j-1]);
}
}
}
int RMQ(int l,int r){
int k = 0;
while((1<<(k+1)) < r - l + 1){
++k;
}
return min(dp[l][k],dp[r-(1<<k) + 1][k]);
}
int main(){
while(~scanf("%d",&n)){
init();
per(i,1,n-1){
int x = 0,y = 0,w = 0;
scanf("%d %d",&x,&y);
add_edge(x,y,w);
++in[y];
}
per(i,1,n){
if(in[i] == 0){
dfs(i);
break;
}
}
ST();
/*
per(i,1,n){
cout << first[i] << " ";
}
cout <<endl;
*/
int q = 0;
scanf("%d",&q);
per(i,1,q){
int x = 0,y = 0;
scanf("%d %d",&x,&y);
int ans = RMQ(min(first[x],first[y]),max(first[x],first[y]));
printf("%d\n",ans);
}
}
return 0;
}
/*
9
1 2
1 3
2 4
2 5
5 7
5 8
7 9
3 6
4
9 8
4 6
2 7
5 3
ans:
first: 1 6 2 15 7 3 10 8 11 -1
5
1
2
1
*/