加边的无向图(并查集)

原题链接
https://ac.nowcoder.com/acm/problem/14685

思路
并查集模板题,只需要把有边连接的点都添加到一个祖宗节点下,然后扫一遍所有点,只要遇到祖宗节点不是起始点的就添加一条边。

代码

#include <iostream>

using namespace std;

const int N = 100010;

int p[N];

int find(int x)
{
    if (x != p[x]) p[x] = find(p[x]);
    return p[x];
}

int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= n; i ++ ) p[i] = i;
    
    while (m -- )
    {
        int a, b;
        cin >> a >> b;
        a = find(a), b = find(b);
        if (a != b) p[a] = b;
    }
    
    int res = 0;
    int px = find(1);
    for (int i = 2; i <= n; i ++ )
        if (find(i) != px)
        {
            res ++ ;
            p[find(i)] = px;
        }
        
    cout << res << endl;
    
    return 0;
}
posted on 2021-04-25 18:24  Laurance  阅读(76)  评论(0)    收藏  举报