并查集模板题 HDU1856 More is better

这里写图片描述


题解:
并查集模板,我卡了一会。。树的高度那里。
还是不够熟悉。
另外,这题直接cin会超时 ,需要加上一句开关。
耗时从1000+到234ms


#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 t;
    int n,m;
    while(cin>>t)
    {
        ini(maxn);
        int flen=0;
        for(int i=0;i<t;++i)
        {
            cin>>n>>m;
            flen=max(flen,n);
            flen=max(flen,m);
            Union(n,m);
        }
        int maxnum=1;
        for(int i=1;i<=flen;++i)
            if(len[i]>maxnum)
                maxnum=len[i];
        cout<<maxnum<<endl;
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值