CodeForces - 580C (DFS)

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 

using namespace std;

const int maxn = 2e5+10;
int cat[maxn];
vector  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> n >> m;
    for ( int i=1; i<=n; i++ ) {
        cin >> cat[i];
    }
    for ( int i=0; i> 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;
}

 

你可能感兴趣的:(CodeForces,Div.2)