1. 程式人生 > 其它 >2021-7-29 Kefa and Park

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 ofnvertices with the root at vertex1. Vertex1also 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 thanmconsecutivevertices with cats.

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

Input

The first line contains two integers,nandm(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 containsnintegersa1, a2, ..., an, where eachaieither equals to0(then vertexihas no cat), or equals to1(then vertexi

has a cat).

Nextn - 1lines contains the edges of the tree in the format "xiyi" (without the quotes) (1 ≤ xi, yi ≤ n,xi ≠ yi), wherexiandyiare 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 mostmconsecutive 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 }