题目:Problem - 580C - Codeforces
题目大意:小k的家在一棵树的根节点上,这棵树的每个叶子节点上有一个饭店,并且在每一个节点上可能有一只猫,小k很害怕猫 因为他是个老鼠,在他从家去饭店的路径不能有连续超过m只猫,求小k可以去到的饭店数量。
题解:树上深搜(dfs)。用vector向量存图,搜索每一条路径,满足条件的计入答案。
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5+10;
int cat[N],leaf[N], vis[N];//是否有猫;是否是叶子节点;是否遍历过
vector<int>e[N];
int n, m, ans;
void dfs(int x,int cnt){
if(vis[x]) return;
else vis[x] = 1;
if(cat[x]) cnt++;
else cnt = 0;
if(cnt > m) return;
else if(leaf[x] == 1 && x != 1) ans++;
for(int i = 0; i < (int)e[x].size(); ++i){
dfs(e[x][i],cnt);
}
return;
}
int main(){
cin>>n>>m;
for(int i = 1; i <= n; ++i){
cin>>cat[i];
}
for(int i = 1; i < n; ++i){
int x, y;
cin>>x>>y;
leaf[x]++;
leaf[y]++;
e[x].push_back(y);
e[y].push_back(x);
}
dfs(1, 0);
cout<<ans<<endl;
}