• 环形连通分量(环的性质)


    题意

    给定一个\(n\)个点\(m\)条边组成的无重边无自环的无向图。请你计算,其包含的所有连通分量中,有多少个是环形的。

    我们认为一个连通分量是环形的,当且仅当它的所有顶点重新排序后,可以满足:

    • 第一个顶点通过一条边与第二个顶点相连。
    • 第二个顶点通过一条边与第三个顶点相连。
    • \(\dots\)
    • 最后一个顶点通过一条边与第一个顶点相连。
    • 所有上述提到的边各不相同。
    • 连通分量中不包含除上述边以外的任何其他边。

    根据定义,任何环形连通分量都至少包含三个顶点。

    题目链接:https://www.acwing.com/problem/content/4496/

    数据范围

    \(1 \leq n \leq 2 \times 10^5\)
    \(0 \leq m \leq 2 \times 10^5\)

    思路

    这道题不难,但是很有意思,所以还是值得记录一下的。

    如果是一个环形连通分量的话,需要满足每个点的度数为\(2\)

    因为BFS搜索每一个连通分量,判断即可。

    代码

    #include <iostream>
    #include <cstring>
    #include <cstdio>
    #include <algorithm>
    #include <queue>
    
    using namespace std;
    
    const int N = 200010, M = 2 * N;
    
    int n, m;
    int h[N], e[M], ne[M], idx;
    int d[N];
    bool st[N];
    
    void add(int a, int b)
    {
        e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
    }
    
    bool bfs(int u)
    {
        queue<int> que;
        que.push(u);
        st[u] = true;
        bool flag = true;
        while(que.size()) {
            int t = que.front();
            que.pop();
            if(d[t] != 2) flag = false;
            for(int i = h[t]; ~i; i = ne[i]) {
                int j = e[i];
                if(!st[j]) {
                    que.push(j);
                    st[j] = true;
                }
            }
        }
        return flag;
    }
    
    int main()
    {
        scanf("%d%d", &n, &m);
        memset(h, -1, sizeof h);
        for(int i = 0; i < m; i ++) {
            int a, b;
            scanf("%d%d", &a, &b);
            add(a, b), add(b, a);
            d[a] ++, d[b] ++;
        }
        int ans = 0;
        for(int i = 1; i <= n; i ++) {
            if(!st[i]) {
                ans += bfs(i);
            }
        }
        printf("%d\n", ans);
        return 0;
    }
    
  • 相关阅读:
    jmeter测试get post 笔记
    Fiddler发送get post测试 笔记
    jmeter json乱码
    IDEA+selenium3+火狐/谷歌驱动 JAVA初步环境搭建 笔记
    java源代码
    java测试
    考试感受
    周进度总结
    周进度总结
    周进度总结
  • 原文地址:https://www.cnblogs.com/miraclepbc/p/16462703.html
Copyright © 2020-2023  润新知