Codeforces 982 C. Cut 'em all!(dfs)

解题思路:

  代码中有详细注解,以任意一点为根,dfs遍历这棵树。

  每一个节点可能有好几个子树,计算每棵子树含有的节点数,再+1即为这整棵树的节点。

  判断子树是否能切断与根之间的联系,如果子树含有偶数个节点,则这棵子树可以被切断。

注意:

  若由于我们建立这棵树的时候不知道两个连接的节点谁是谁的父节点。

  所以我们在dfs中加个标记,找出除父节点以外的其他节点。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

list<int> l[100010];

int ans = 0;
int dfs(int u, int v){
    int sum = 0;
    for(list<int>::iterator it = l[u].begin();it != l[u].end(); it++){
        if(v != *it){    //封闭往回找,以免形成环。 
            int ret = dfs(*it, u);
            sum += ret;    //sum统计以u为根的子树总共有多少节点。 
            if(ret%2 == 0) ans++;//如果u节点连接的某棵子树含有偶个节点,则可以切断, 
        }
    }
    return sum+1;//加上本身 
}

int main(){
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    int u, v;
    int t = n-1;
    while(t--){
        cin >> u >> v;
        l[u].push_back(v);
        l[v].push_back(u);
    }
    if(n & 1){
        cout << -1 << endl;
        return 0;
    }
    dfs(1, 100010);
    cout << ans << endl; 
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zhangjiuding/p/9057436.html