题解:set就好
#include<iostream> #include<cstdio> #include<map> #include<cstring> using namespace std; const int maxn=100009; int n,k; int root; int w[maxn]; int notroot[maxn]; int ans; int cntedge; int head[maxn]; int to[maxn<<1],nex[maxn<<1]; void Addedge(int x,int y){ nex[++cntedge]=head[x]; to[cntedge]=y; head[x]=cntedge; } map<int,int>ma; void Dfs(int x,int fa,int sum){ if(ma[sum-k]!=0)++ans; ma[sum]++; for(int i=head[x];i;i=nex[i]){ if(to[i]==fa)continue; Dfs(to[i],x,sum+w[to[i]]); } ma[sum]--; } int main(){ scanf("%d%d",&n,&k); for(int i=1;i<=n;++i)scanf("%d",&w[i]); for(int i=1;i<=n-1;++i){ int x,y; scanf("%d%d",&x,&y); Addedge(x,y); notroot[y]=1; } for(int i=1;i<=n;++i)if(notroot[i]==0)root=i; ma[0]=1; Dfs(root,0,w[root]); printf("%d\n",ans); return 0; }