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
123
124
125
126
127
128
129
130
|
#include <bits/stdc++.h>
#define mk(x,y) make_pair(x,y)
#define pll pair<ll,ll>
#define pii pair<int,int>
#define max(x,y) ((x)<(y)?(y):(x))
#define min(x,y) ((x)>(y)?(y):(x))
using namespace std;
typedef long long ll;
typedef double db;
#define int long long
const int N=1e6+7,mod=998244353;
const int inf=1e14+7;
int f[N][21][3],dep[N];
pii g[N][2];
vector<int> nx[N];
bool bk[N];
int n,m;
void dfs(int x,int fa,int last)
{
dep[x]=dep[fa]+1;
if(bk[x]) last=0,g[x][0]=mk(0,x);
else ++last;
f[x][0][0]=fa;
for(auto y:nx[x]) {
if(y==fa) continue;
dfs(y,x,last);
if(g[y][0].first+1<g[x][0].first) g[x][0]=mk(g[y][0].first+1,y);
}
for(auto y:nx[x]) {
if(y==fa||y==g[x][0].second) continue;
if(g[y][0].first+1<g[x][1].first) g[x][1]=mk(g[y][0].first+1,y);
}
}
void dfs2(int x,int fa,int last)
{
if(x!=1) {
int k=0;
if(g[fa][0].second==x) k=1;
if(g[fa][k].first+1<g[x][0].first) {
g[x][1]=g[x][0];
g[x][0]=mk(g[fa][k].first+1,fa);
} else if(g[fa][k].first+1<g[x][1].first) {
g[x][1]=mk(g[fa][k].first+1,fa);
}
}
for(auto y:nx[x]) {
if(y==fa) continue;
dfs2(y,x,last);
}
f[x][0][1]=min(f[x][0][1],g[x][0].first*3+n-dep[x]);
f[x][0][2]=min(f[x][0][2],g[x][0].first*3+dep[x]);
}
int LCA(int x,int y)
{
if(dep[x]<dep[y]) swap(x,y);
for(int i=20;i>=0;--i)
if(dep[f[x][i][0]]>=dep[y]) {
x=f[x][i][0];
}
if(x==y) {
return x;
}
for(int i=20;i>=0;--i)
if(f[x][i][0]!=f[y][i][0]) {
x=f[x][i][0];y=f[y][i][0];
}
return f[x][0][0];
}
void solve()
{
cin>>n>>m;
for(int i=1;i<n;++i) {
int x,y;
cin>>x>>y;
nx[x].push_back(y);
nx[y].push_back(x);
}
for(int i=0;i<=n;++i) {
g[i][0]=g[i][1]=mk(inf,0);
for(int j=0;j<=20;++j) f[i][j][1]=inf,f[i][j][2]=inf;
}
for(int i=1;i<=m;++i) {
int x;
cin>>x;
bk[x]=1;
}
dfs(1,0,inf);
dfs2(1,0,inf);
for(int j=1;j<=20;++j)
for(int i=1;i<=n;++i) {
f[i][j][0]=f[f[i][j-1][0]][j-1][0];
f[i][j][1]=min(f[i][j-1][1],f[f[i][j-1][0]][j-1][1]);
f[i][j][2]=min(f[i][j-1][2],f[f[i][j-1][0]][j-1][2]);
}
int q;
cin>>q;
while(q--) {
int x,y;
cin>>x>>y;
int lca=LCA(x,y);
int ans=dep[x]+dep[y]-dep[lca]*2,mi=f[lca][0][1]-n+dep[x],tmpx=x,tmpy=y;
for(int i=20;i>=0;--i)
if(dep[f[tmpx][i][0]]>=dep[lca]) {
mi=min(mi,f[tmpx][i][1]-n+dep[x]);
tmpx=f[tmpx][i][0];
}
for(int i=20;i>=0;--i)
if(dep[f[tmpy][i][0]]>=dep[lca]) {
mi=min(mi,f[tmpy][i][2]-dep[lca]+dep[x]-dep[lca]);
tmpy=f[tmpy][i][0];
}
ans+=mi;
ans=min(ans,(dep[x]+dep[y]-dep[lca]*2)*2);
printf("%lld\n",ans);
}
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int T=1;
// cin>>T;
while(T--) {
solve();
}
return 0;
}
|