HDU 1213 How Many Tables

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1213

题记:用并查集即可。

#include<bits/stdc++.h>

using namespace std;
const int maxn=1050;
int s[maxn];

void init_set(){
    for(int i=1;i<=maxn;i++)
        s[i]=i;
}

int find_set(int x){
    return x==s[x]?x:find_set(s[x]);//判断是否指向自己,返回这个集合中指向自己的数
}

void union_set(int x,int y){
    x=find_set(x);
    y=find_set(y);
    if(x!=y)s[x]=s[y];
}

int main(){
    int t,n,m,x,y;
    cin>>t;
    while(t--){
        cin>>n>>m;
        init_set();//初始化
        for(int i=1;i<=m;i++){
            cin>>x>>y;
            union_set(x,y);
        }
        int ans=0;
        for(int i=1;i<=n;i++)
            if(s[i]==i)
                ans++;
        cout<<ans<<endl;
    }
    return 0;
}

优化:查找find_set和合并union_set复杂度都是O(n)
下面优化可以达到小于O(log2 n)

合并的优化:

int height[maxn];//定义元素i的高度,合并时更改
void init_set(){
    for(int i=1;i<=maxn;i++){
        s[i]=i;
        height[i]=0;
    }
}
void union_set(int x,int y){
    x=find_set(x);
    y=find_set(y);
    if(height[x]==height[y]){
        height[x]=height[x]+1;
        s[y]=x;
    }
    else{
        if(height[x]<height[y])s[x]=y;
        else s[y]=x;
    }
}

查询的优化

int find_set(int x){
    if(x!=s[x])s[x]=find_set(s[x]);
    return s[x];
}
int find_set(int x){
    int r=x;
    while(s[r]!=r)r=s[r];
    int i=x,j;
    while(i!=r){
        j=s[i];
        s[i]=r;
        i=j;
    }
    return r;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值