在对树进行遍历时记录一下这个点的父亲点权是不是 (1)、当前连续点权为 (1) 的节点个数、根到当前结点的路径上连续点权为 (1) 的最多节点个数,然后直接对叶子节点统计答案即可。
#include <bits/stdc++.h>
#define DEBUG fprintf(stderr, "Passing [%s] line %d
", __FUNCTION__, __LINE__)
#define File(x) freopen(x".in","r",stdin); freopen(x".out","w",stdout)
using namespace std;
typedef long long LL;
typedef pair <int, int> PII;
typedef pair <int, PII> PIII;
inline int gi()
{
int f = 1, x = 0; char c = getchar();
while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return f * x;
}
inline LL gl()
{
LL f = 1, x = 0; char c = getchar();
while (c < '0' || c > '9') {if (c == '-') f = -1; c = getchar();}
while (c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return f * x;
}
const int INF = 0x3f3f3f3f, N = 100003, M = N << 1;
int n, m;
int tot, head[N], ver[M], nxt[M];
int qz[N];
int lx[N];
inline void add(int u, int v)
{
ver[++tot] = v, nxt[tot] = head[u], head[u] = tot;
}
void dfs(int u, int f, int now/*当前连续点权为 1 的节点个数*/, bool lst/*当前节点的父亲的点权是不是 1*/, int mxnow/*根到当前节点的路径上点权为 1 的最多节点个数*/)
{
lx[u] = mxnow; //记录最多的节点个数
for (int i = head[u]; i; i = nxt[i])
{
int v = ver[i];
if (v == f) continue;
//分情况讨论递归
if (qz[v] == 1)
dfs(v, u, lst ? now + 1 : 1, true, max(mxnow, lst ? now + 1 : 1));
else
dfs(v, u, 0, false, mxnow);
}
}
bool fl[N];
inline void dfss(int u, int f)
{
for (int i = head[u]; i; i = nxt[i])
{
int v = ver[i];
if (v == f) continue;
fl[u] = true;
dfss(v, u);
}
}
int main()
{
//File("");
n = gi(), m = gi();
for (int i = 1; i <= n; i+=1) qz[i] = gi();
for (int i = 1; i < n; i+=1)
{
int u = gi(), v = gi();
add(u, v), add(v, u);
}
dfss(1, 0);
dfs(1, 0, qz[1], (qz[1] == 1), qz[1]);
int ans = 0;
for (int i = 1; i <= n; i+=1)
{
if (!fl[i] && lx[i] <= m) ++ans; //对符合要求的叶子节点计数
}
printf("%d
", ans);
return 0;
}