2021-7-29 Kefa and Park

难度 1500

题目 Codeforces:

C. Kefa and Park time limit per test 2 seconds memory limit per test 256 megabytes   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 ≤ 105, 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 ≤ nxi ≠ 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.

Keyword

vertices 结点

guaranteed 保证

 

题目解析

本题大意就是dfs的模板题,只不过在其中加了一些条件,即一条完整到达叶的路径上的连续的特殊节点不能超过m个,即题目种所说的连续的猫不能超过m个。

算是很基础的dfs吧,值得一题的是,这里我是用到vector来存储节点,然后两个bool数组来分别作为标记数组和特殊节点数组,这里同样可以使用bitset来节省内存,可以但没必要,然后最后这题理解题意的时候要注意,是连续的猫不能超过m个,而且返回的是要去掉特殊节点的节点数。

解析完毕,以下是参考代码,不说了,打比赛去了

 1 #include<iostream>
 2 #include<string>
 3 #include<vector>
 4 using namespace std;
 5 int n, m, x, y, ans = 0;
 6 bool cat[100001];
 7 bool book[100001];
 8 vector<int>mp[100001];
 9 void dfs(int temp,int cnt)
10 {
11     if (cnt <= m)
12     {
13         bool tf = 1;
14         int length = mp[temp].size();
15         for (int i = 0; i < length; i++)
16         {
17             int a = mp[temp][i];
18             if (!book[a])
19             {
20                 book[a] = 1;
21                 tf = 0;
22                 if (cat[a])dfs(a, cnt+1);
23                 else dfs(a, 0);
24             }
25         }
26         if (tf)ans++;
27     }
28     
29 }
30 int main()
31 {
32     cin >> n >> m;//n个点,路径上不能超过m只猫
33     for (int i = 1; i <= n; i++)cin >> cat[i];
34     for (int i = 1; i <= n-1; i++)
35     {
36         cin >> x >> y;
37         mp[x].push_back(y);
38         mp[y].push_back(x);
39     }
40     book[1] = 1;
41     dfs(1, cat[1]);
42     cout << ans << endl;
43     return 0;
44 }

 

上一篇:prim最小生成树代码


下一篇:TZOJ6128: Graph Coloring(树形DP)