Codeforces Round #321 (Div. 2)C(tree dfs)

题意:给出一棵树,共有n个节点,其中根节点是Kefa的家,叶子是restaurant,a[i]....a[n]表示i节点是否有猫,问:Kefa要去restaurant并且不能连续经过m个有猫的节点有多少条路径;

思路:先用vector数组建树; 再dfs..(第一次用vector建树,还看了别人的代码,果然是zz);

代码:

 1 #include <bits/stdc++.h>
 2 #define ll long long
 3 #define MAXN 100000+10
 4 using namespace std;
 5 
 6 vector<int>tree[MAXN];
 7 int a[MAXN], vis[MAXN], n, k;
 8 ll ans;
 9 
10 void dfs(int cnt, int num)
11 {
12     if(vis[cnt]||num>k) return;
13     if(tree[cnt].size()==1&&cnt!=1) ans++;
14     vis[cnt]++;
15     for(int i=0; i<tree[cnt].size(); i++)
16     {
17         if(!vis[tree[cnt][i]])
18         {
19             if(!a[tree[cnt][i]]) dfs(tree[cnt][i], 0);
20             else dfs(tree[cnt][i], num+1);
21         }
22     }
23 }
24 
25 int main(void)
26 {
27     memset(vis, 0, sizeof(vis));
28     cin >> n >> k;
29     for(int i=1; i<=n; i++)
30     {
31         tree[i].clear();
32         cin >> a[i];
33     }
34     for(int i=1; i<n; i++)
35     {
36         int x, y;
37         cin >> x >> y;
38         tree[x].push_back(y);
39         tree[y].push_back(x);
40     }
41     ans=0;
42     dfs(1, a[1]);
43     cout << ans << endl;
44     return 0;
45 }

 



posted @ 2016-08-31 22:27  geloutingyu  阅读(234)  评论(0编辑  收藏  举报