• Codeforces --- 982C Cut 'em all! DFS加贪心


    题目链接:

    https://cn.vjudge.net/problem/1576783/origin

    输入输出:

    Examples
    inputCopy
    4
    2 4
    4 1
    3 1
    outputCopy
    1
    inputCopy
    3
    1 2
    1 3
    outputCopy
    -1
    inputCopy
    10
    7 1
    8 4
    8 10
    4 7
    6 5
    9 3
    3 5
    2 10
    2 5
    outputCopy
    4
    inputCopy
    2
    1 2
    outputCopy
    0
    Note
    In the first example you can remove the edge between vertices 11 and 44. The graph after that will have two connected components with two vertices in each.

    In the second example you can't remove edges in such a way that all components have even number of vertices, so the answer is −1

    题目大意:

    这道题其实题意很简单,给你一棵树,让你删边,然后得到的子树节点个数要是偶数

    而边的个数在离散数学里定义是 m = n-1, 这个在建树的时候需要注意!

    DFS的作用是统计这个节点连接的节点的个数,具体实现在代码中有注释。

    下面是AC代码:

    #include <iostream>
    #include <cstdio>
    #include <vector>
    #define pb push_back
    #include <string.h>
    
    using namespace std;
    const int MX = 1e5+10;
    int vis[MX], sum[MX];
    int n;
    vector<int> G[MX];
    
    int dfs(int x)
    {
        for(int i = 0; i < G[x].size(); ++i)
        {
            int u = G[x][i];
            if(!vis[u])
            {
                vis[u] = 1; // 经过的点先标记一下
                sum[x] += dfs(u); //沿着点DFS
                vis[u] = 0; // 回溯
            }
        }
        sum[x]++; // 经过一个点则需要加一
        return sum[x];
    }
    
    int main()
    {
        int ans = 0;
        memset(vis, 0, sizeof(vis));
        memset(sum, 0, sizeof(sum));
        scanf("%d", &n);
        for(int i = 1; i <= n-1; ++i) // 建树初始化m = n-1
        {
            int u, v;
            scanf("%d%d", &u, &v);
            G[u].pb(v);
            G[v].pb(u); // 无向图!
        }
        if(n%2) //节点为奇数则不可能都分为偶数节点的连通图
        {
            printf("-1
    ");
            return 0;
        }
        vis[1] = 1; // 初始节点的vis先标记为一
        dfs(1);
        for(int i = 1; i <= n; ++i)
        {
            //cout << sum[i] << ' ';
            if(sum[i]%2 == 0) ans++; // 节点个数为偶数则减
        }
        //cout << endl;
        printf("%d
    ", ans-1); //减一的理由是根节点节点数一定为偶数,但是其不能减。。
    }
    View Code

    如有疑问,欢迎评论指出!

    化繁为简 大巧不工
  • 相关阅读:
    【POJ1961】period
    主席树入门
    noip模拟【tea】
    noip模拟【service】
    noip模拟【noname】
    clearfix清除浮动
    九大内置对象
    2017/10/10 jar包错误
    mybatis案例源码详解
    自动类型转换
  • 原文地址:https://www.cnblogs.com/mpeter/p/10295797.html
Copyright © 2020-2023  润新知