CodeForces - 580C (BFS)
题目链接:http://codeforces.com/contest/580/problem/C
题意:n个点,给n-1条边,构成以1为节点的树。人在1节点想去叶节点,但是害怕猫,所以在去叶节点的路上不能出现连续的超过m只猫。问可以去几个叶节点。
思路:n是2e5的,用vector存图,dfs或者bfs都行,从根节点开始遍历。叶节点的特征是只有一个相邻的点,并且不是根节点if(node!=1 && a[node].size()==1)
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5+10;
int cat[maxn];
vector <int> a[maxn];
int ans;
int n,m;
void dfs( int node, int fa, int lcat )
{
if ( lcat>m ) { // 如果连续的猫太多,return
return ;
}
if ( a[node].size()==1 && node!=1 ) { // 判断是否是叶节点
ans ++;
return ;
}
for ( int i=0; i<a[node].size(); i++ ) {
if ( a[node][i]==fa ) { // 不去遍历父亲节点
continue ;
}
int t = a[node][i];
if ( cat[t]==0 ) { // 如果不连续就清零一下
dfs( t,node,cat[t] );
}
else {
dfs( t,node,lcat+cat[t] );
}
}
}
int main()
{
int x,y;
cin >> n >> m;
for ( int i=1; i<=n; i++ ) {
cin >> cat[i];
}
for ( int i=0; i<n-1; i++ ) {
cin >> x >> y;
a[x].push_back(y); // vector存图
a[y].push_back(x);
}
ans = 0;
dfs(1,-1,cat[1]);
cout << ans << endl;
return 0;
}