点分治

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
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
#include<string>
#include<cstring>
#include<map>
using namespace std;
#define ll long long
#define R register
#define fo(a,b,c) for(R int a=b;a<=c;++a)
#define mmt(x,y) memset(x,y,sizeof(x))
#define dbg(x) cout<<#x<<" = "<<x<<'\n'
#define maxn 400080
int head[maxn>>2],to[maxn],nxt[maxn],tot=1,n,m,ans[maxn],que[maxn];
int siz[maxn],f[maxn],dis[maxn],q[maxn],rt,val[maxn],nodenum;
bool vis[maxn>>2];
map<int,int>mp;
void add(int x,int y,int z){nxt[++tot]=head[x];head[x]=tot;to[tot]=y;val[tot]=z;}
void getrot(int x,int fa)
{
siz[x]=1;f[x]=0;
for(int i=head[x];i;i=nxt[i])
if(!vis[to[i]]&&to[i]!=fa)
{
getrot(to[i],x);
siz[x]+=siz[to[i]];
f[x]=max(f[x],siz[to[i]]);
}
f[x]=max(f[x],nodenum-siz[x]);
if(f[x]<f[rt])rt=x;
}
void getdis(int x,int fa)
{
q[++q[0]]=dis[x];
for(int i=head[x];i;i=nxt[i])
if(!vis[to[i]]&&to[i]!=fa)
dis[to[i]]=dis[x]+val[i],getdis(to[i],x);
}
int getsiz(int x,int fa)
{
R int res=1;
for(int i=head[x];i;i=nxt[i])
if(to[i]!=fa&&!vis[to[i]])
res+=getsiz(to[i],x);
return res;
}
void dfs(int x)
{
vis[x]=1;
mp.clear();mp[0]=1;
for(int i=head[x];i;i=nxt[i])
{
if(!vis[to[i]])
{
dis[to[i]]=val[i];q[0]=0;
getdis(to[i],x);
sort(q+1,q+1+q[0]);
fo(k,1,m)
if(!ans[k])
fo(j,1,q[0])
if(mp[que[k]-q[j]])ans[k]=1;
}
fo(j,1,q[0])mp[q[j]]=1;
}
for(int i=head[x];i;i=nxt[i])
if(!vis[to[i]])
{
nodenum=getsiz(to[i],to[i]);
rt=0;getrot(to[i],x);
dfs(rt);
}
}
int main()
{
scanf("%d%d",&n,&m);
fo(i,2,n)
{
R int x,y,z;scanf("%d%d%d",&x,&y,&z);
add(x,y,z);add(y,x,z);
}
fo(i,1,m)scanf("%d",&que[i]);
rt=0;nodenum=n;
f[0]=1e9;
getrot(1,0);
dfs(rt);
fo(i,1,m)
{
if(ans[i])puts("AYE");
else puts("NAY");
}
return 0;
}
显示 Gitment 评论