P1536 村村通 【并查集求连通块个数】

题目

https://www.luogu.com.cn/problem/P1536

 

 这道题第一眼的思路感觉是最小生成树,但是发现它的边没有权值,所以这道题的问题是求解这个图的连通块的个数,而需要连接的道路条数就是连通块的个数减一

代码

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
using namespace std;
int father[6000], ranks[6000];
int find(int x)
{
    if (father[x] == x)return x;
    return father[x] = find(father[x]);
}
void merge(int x, int y)
{
    int a = find(x);
    int b = find(y);
    if (a == b)return;
    if (ranks[a] > ranks[b])father[b] = a;
    else
    {
        father[a] = b;
        if (ranks[a] == ranks[b])ranks[b]++;
    }
}

int main()
{
    int n, m;
    while (1)
    {
        cin >> n;
        if (n == 0)return 0;
        cin >> m;
        for (int i = 1; i <= n; i++)father[i] = i;
        for (int i = 0; i < m; i++)
        {
            int a, b;
            scanf("%d%d", &a, &b);
            merge(a, b);
        }
        int count = 0;
        for (int i = 1; i <=n; i++)
        {
            if (father[i] == i)count++;
        }
        printf("%d\n", count-1);
    }

}

 

posted @ 2020-06-28 21:01  Jason66661010  阅读(172)  评论(0编辑  收藏  举报