第四周训练 | 并查集

随声附和 提交于 2019-12-05 18:12:04

 A - How Many Tables

#include<iostream>
using namespace std;
const int maxn = 1050;
int set[maxn];
void init_set()
{
    for(int i=0;i<=maxn;++i)set[i]=i;    
}
int find_set(int x)
{
    return x==set[x]?x:find_set(set[x]);
} 
void union_set(int x,int y)
{
    x=find_set(x);
    y=find_set(y);
    if(x!=y)set[x]=set[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(set[i]==i)ans++;
        }
        cout<<ans<<endl;
    }
    return 0;
}

 优化版,降低了树高

#include<iostream>
using namespace std;
const int maxn = 1050;
int set[maxn],height[maxn];
void init_set()
{
    for(int i=0;i<=maxn;++i)
    {
        set[i]=i;
        height[i]=0;
    }    
}
int find_set(int x)
{
    return x==set[x]?x:find_set(set[x]);
} 
void union_set(int x,int y)
{
    x=find_set(x);
    y=find_set(y);
    if(height[x]==height[y])
    {
        height[x]+=1;
        set[y]=x;
    }
    else
    {
        if(height[x]<height[y])set[x]=y;
        else set[y]=x;
    }

}

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(set[i]==i)ans++;
        }
        cout<<ans<<endl;
    }
    return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!