题目链接:http://codeforces.com/problemset/problem/580/C点击打开链接
用dfs
然后注意所给两个节点没有从属关系因此不需要并查集
判断叶子的条件为是否只存在一个相连节点并且那个节点已经被判断过
#include <bits/stdc++.h>
using namespace std;
vector<int> s[222222];
int vis[222222];
int val[222222];
int ans;
int n,m;
void dfs(int now,int num)
{
if(num>m)
return;
if(s[now].size()==1&&vis[s[now][0]])
{
ans++;
return;
}
for(int i=0;i<s[now].size();i++)
{
if(vis[s[now][i]]==0)
{
vis[s[now][i]]=1;
int mid;
if(val[s[now][i]])
mid=num+val[s[now][i]];
else
mid=0;
dfs(s[now][i],mid);
}
}
}
int main()
{
cin >> n >> m;
for(int i=1;i<=n;i++)
{
cin >> val[i];
}
for(int i=0;i<n-1;i++)
{
int mid1,mid2;
cin >> mid1 >> mid2;
s[mid1].push_back(mid2);
s[mid2].push_back(mid1);
}
int root=1;
vis[root]=1;
dfs(root,val[root]);
cout << ans << endl;
}