POJ1611 The Suspects

本文介绍了一个使用并查集算法解决图论中连通性问题的C++实现案例。通过输入顶点数量和边的数量,程序能够处理一系列边的连接操作,并最终输出整个图的连通组件数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
const int maxn = 30100;
const int bound = 30001;
int gn, gm;
int f[maxn], cnt[maxn];
vector<int> v;

int getFather(int x) {
    if(x == f[x]) return x;
    else return f[x] = getFather(f[x]);
}

int main()
{
    int k, input;
    while(scanf("%d%d", &gn, &gm) == 2 && (gn || gm)) {
        for(int i = 0; i <= bound; i++) { f[i] = i; cnt[i] = 1; }
        for(int i = 0; i < gm; i++) {
            scanf("%d", &k);
            v.clear();
            for(int j = 0; j < k; j++) {
                scanf("%d", &input);
                v.push_back(input);
            }
            if(k==1) continue;
            else {
                int first = v[0];
                for(int t = 1; t < (int)v.size(); t++) {
                    int parent = getFather(first);
                    int parentx = getFather(v[t]);
                    if(parent == parentx) continue;
                    else {
                        cnt[parent] += cnt[parentx];
                        f[parentx] = parent;
                    }
                }
            }
        }
        int parent = getFather(0);
        printf("%d\n", cnt[parent]);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值