请看julao的解释吧,讲的挺清楚的
https://blog.csdn.net/a_forever_dream/article/details/81778649
#include<bits/stdc++.h>
using namespace std;
int n,m,cnt,Size;
struct node{
int x,y,z,nxt;
}e[20005];
int lnk[10005];
int root,ms,size[10005],mson[10005],sum[10000005],ask[105],ans[105];
bool vis[10005];
inline int read(){
int ret=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch='-')f=-f;ch=getchar();}
while(ch<='9'&&ch>='0')ret=ret*10+ch-'0',ch=getchar();
return ret*f;
}
void add_e(int x,int y,int z){
cnt++;e[cnt].x=x;e[cnt].y=y;e[cnt].z=z;e[cnt].nxt=lnk[x];lnk[x]=cnt;
}
void getroot(int x,int fa){
size[x]=1;mson[x]=0;
for(int j=lnk[x];j;j=e[j].nxt){
if(vis[e[j].y]||e[j].y==fa)continue;
getroot(e[j].y,x);
size[x]+=size[e[j].y];
if(size[e[j].y]>mson[x])mson[x]=size[e[j].y];
}
if(Size-size[x]>mson[x])mson[x]=Size-size[x];
if(ms>mson[x])ms=mson[x],root=x;
}
int t;
int dis[10005];
void getdis(int x,int fa,int z){
dis[++t]=z;
for(int j=lnk[x];j;j=e[j].nxt){
if(e[j].y==fa||vis[e[j].y])continue;
getdis(e[j].y,x,z+e[j].z);
}
}
struct AS{
int x,y;
}arr[10005];
int tt;
void solve(int x,int y,int id){
t=0;
getdis(x,0,y);
tt=0;
sort(dis+1,dis+t+1);
dis[0]=-1;
for(int i=1;i<=t;i++)if(dis[i]!=dis[i-1])arr[++tt].x=dis[i],arr[tt].y=1;
else arr[tt].y++;
for(int i=1;i<=m;i++){
if(ask[i]&1==0)
for(int j=1;j<=tt;j++)
if(arr[j].x==ask[i]/2)ans[i]+=(arr[j].y-1)*arr[j].y*id;
for(int j=1;j<=tt&&arr[j].x<ask[i]/2;j++){
int l=j+1,r=tt;
while(l<=r){
int mid=(r-l>>1)+l;
if(arr[j].x+arr[mid].x==ask[i]){
ans[i]+=arr[j].y*arr[mid].y*id;
break;
}
if(arr[j].x+arr[mid].x>ask[i])r=mid-1;
else l=mid+1;
}
}
}
}
void fenzhi(int x,int ssize){
vis[x]=1;
solve(x,0,1);
for(int j=lnk[x];j;j=e[j].nxt){
if(vis[e[j].y])continue;
solve(e[j].y,e[j].z,-1);
ms=1<<30;root=0;
Size=size[e[j].y]<size[x]?size[e[j].y]:(ssize-size[x]);
getroot(e[j].y,0);
fenzhi(root,Size);
}
}
int main(){
freopen("P3806.in","r",stdin);
freopen("P3806.out","w",stdout);
n=read();m=read();
for(int i=1;i<n;i++){
int x,y,z;
x=read(),y=read(),z=read();
add_e(x,y,z);add_e(y,x,z);
}
for(int i=1;i<=m;i++)ask[i]=read();
root=0;ms=1<<30;Size=n;
getroot(1,0);
fenzhi(root,n);
for(int i=1;i<=m;i++)
if(ans[i]>0)printf("AYE
");
else printf("NAY
");
return 0;
}