并查集模板题 HDU1232 畅通工程

这里写图片描述


题解:
计算不在并查集中元素的个数,F[i]=i的,减去一个爸爸,就是最终结果
比如数据
3 1
1 2
有3个城市,1 2连起来的
那么F[1]=2;F[2]=2;F[3]=3;
就是2-1=1
还要建一条


#include<bits/stdc++.h>
using namespace std;

const int maxn=100010;
int F[maxn];
int len[maxn];

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

void Union(int x,int y)
{
    x=f(x);
    y=f(y);
    if(x!=y)
    {
        //cout<<"process "<<x<<" "<<y<<endl;
        //cout<<"F["<<x<<"]="<<f(x)<<endl;
        //cout<<"F["<<y<<"]="<<f(y)<<endl;
        F[x]=y;
        //cout<<"F["<<x<<"]="<<F[x]<<endl;
        len[y]+=len[x];
        //cout<<"len "<<y<<": "<<len[y]<<endl;
    }

}

inline bool same(int x,int y)
{
    return f(x)==f(y);
}

void ini(int n)
{
    for(int i=1;i<=n;++i)
    {
        F[i]=i;
        len[i]=1;
    }
}

int main()
{
    std::ios::sync_with_stdio(false);//不加超时
    int n,m;//n city m road
    while(cin>>n,n)
    {
        cin>>m;
        ini(n);
        int x,y;//city1 city2
        for(int i=0;i<m;++i)
        {
            cin>>x>>y;
            if(!same(x,y))
                Union(x,y);
        }
        int cnt=0;
        for(int i=1;i<=n;++i)
            if(F[i]==i)
                ++cnt;
        cout<<cnt-1<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值