1118. Birds in Forest (25)

本文详细介绍了并查集算法的基本概念、实现原理及其应用。通过具体的C++代码示例,展示了如何利用并查集解决图的连通性问题,包括初始化、查找根节点和合并集合等关键操作。

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

并查集

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int pre[10005];
vector<bool> visited(10005,false);
int findroot(int t)
{
    if (pre[t] != t) pre[t] = findroot(pre[t]);
    return pre[t];
}
void join(int x, int y)
{
    int fx = findroot(x);
    int fy = findroot(y);
    if (fx != fy)
    {
        pre[max(fx, fy)] = min(fx, fy);
    }
}

int main()
{
    int N;
    cin >> N;
    for (int t = 0;t < 10005;t++)
        pre[t] = t;
    while (N--)
    {
        int n;
        cin >> n;
        if (n == 0) continue;
        int x, y;
        cin >> x;
        visited[x] = true;
        while (--n)
        {
            cin >> y;
            join(x, y);
            visited[y] = true;
        }
    }
    int cnt1 = 0,cnt2=0;
    for (int t = 0;t < 10005;t++)
    {
        if (visited[t])
        {
            cnt2 = max(cnt2, t);
            if (pre[t] == t)
                cnt1++;
        }
    }

    cin >> N;
    cout << cnt1 << " " << cnt2 << endl;
    while (N--)
    {
        int a, b;
        cin >> a >> b;
        if (findroot(a) == findroot(b))
            cout << "Yes" << endl;
        else cout << "No" << endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值