Day 37 C. Kefa and Park

Problem
Kefa decided to celebrate his first big salary by going to the restaurant.

He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa’s house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.

The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.

Your task is to help Kefa count the number of restaurants where he can go.

Input
The first line contains two integers, n and m (2 ≤ n ≤ 10^5, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.

The second line contains n integers a1, a2, …, an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).

Next n - 1 lines contains the edges of the tree in the format “xi yi” (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.

It is guaranteed that the given set of edges specifies a tree.

Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa’s home contains at most m consecutive vertices with cats.

Examples
input
4 1
1 1 0 0
1 2
1 3
1 4
output
2

input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
output
2

#include
#include
#include
#include
#include
#include
#include
#include
#include
#define ll long long
using namespace std;
const int maxn = 100005;
bool f[maxn];//标记是否走过 初始值为false true表示为走过
bool fcat[maxn];//记录该节点上是否有猫
int leaf[maxn];
int m;//m表示猫的数量
int n;//n表示节点数量
int ans;//ans表示最后能走到的餐馆
vector<int>v[maxn];
void dfs(int x, int cat)
{
    if (f[x])//如果走过 直接返回
    {
        return;
    }
    else//如果没走过 标记为走过 
    {
        f[x] = true;
    }
    if (fcat[x])//consecutive 连续 用于判断连续碰到猫的数量
    {
        cat++;
    }
    else
    {
        cat = 0;
    }
    if (cat > m)
    {
        return;
    }
    if (leaf[x] < 2 && x != 1)
    {
        ans++;
    }
    for (int i = 0; i < v[x].size(); i++)
    {
        dfs(v[x][i], cat);
    }
    return;
}
int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        cin >> fcat[i];
    }
    for (int i = 0; i < n - 1; i++)
    {
        int a, b;
        cin >> a >> b;
        leaf[a]++;
        leaf[b]++;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    dfs(1, 0);
    cout << ans << endl;
    return 0;
}



你可能感兴趣的:(Codeforces)