2020-10-09 并查集及路径压缩

笔记

在这里插入图片描述

例题

洛谷 P2078 朋友

两个并查集,求数量小的个数。
代码

#include <iostream>

using namespace std;

int father[20005],mather[20005];
int ans1,ans2;
int findx(int x,int parent[])
{
    int r = x;
    while(parent[r]!=r)
    {
        r=parent[r];
    }
    return r;
}
void add(int x,int y)
{
    int xx,yy;
    if(x > 0 && y > 0)
    {
        xx = findx(x,father);
        yy = findx(y,father);
        if(xx!=yy)
        {
            father[xx]=yy;
        }

    }
    else
    {
        xx = findx(-x,mather);
        yy = findx(-y,mather);
        if(xx!=yy)
        {
            mather[xx]=yy;
        }

    }
}
int main()
{
    std::ios::sync_with_stdio(false);
    int n,m,p,q;
    cin >> n >> m >> p >> q;
    for(int i = 1;i<10005;i++)
    {
        father[i]=i;
        mather[i]=i;
    }
    int a,b;
    for(int i = 0;i < p;i++)
    {
        cin >> a >> b;
        add(a,b);
    }
    for(int i = 0;i < q;i++)
    {
        cin >> a >> b;
        add(a,b);
    }
    int one1 = findx(1,father);
    for(int i = 1;i <= n;i++)
    {
        if (one1 == findx(i,father))
        ans1++;
    }
    int one2 = findx(1,mather);
    for(int i = 1;i <= m;i++)
    {
        if (one2 == findx(i,mather))
        ans2++;
    }
    int ans = min(ans1,ans2);
    cout << ans << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值