Codevs4246 奶牛的身高

本文介绍了一种使用带权并查集解决特定问题的方法。通过实例讲解了如何初始化并查集,查找元素的根节点,以及如何进行集合合并等关键操作。代码示例清晰地展示了算法的实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:http://codevs.cn/problem/4246/
分析:带权并查集,注意find中变量不能是全局。
代码:

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int Tmax=30005;
int n,m,fa[Tmax],height[Tmax];
void init()
{
    memset(height,0,sizeof(height));
    int i;
    for(i=1;i<=n;i++) fa[i]=i;
    return;
}
int find(int x)
{
    int oldf,newf;
    if(fa[x]==x) return x;
    oldf=fa[x];
    newf=find(fa[x]);
    height[x]+=height[oldf];
    return fa[x]=newf;
}
int main()
{
    int T,i,u,v,w,fx,fy;
    bool ok;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d",&n,&m);
        init();ok=false;
        for(i=1;i<=m;i++)
        {
            scanf("%d%d%d",&u,&v,&w);
            if(ok) continue;
            if(u==v&&w!=0){
                printf("Bessie is blind.\n");
                ok=true;
                continue;
            }
            fx=find(u);
            fy=find(v);
            if(fx==fy){
                if(height[u]-height[v]!=w){
                    printf("Bessie is blind.\n");
                    ok=true;
                    continue;
                }else continue;
            }
            else {
                fa[fx]=fy;
                height[fx]=w+height[v]-height[u];//height[fx]=w+height[v];
            }
        }
        if(!ok) printf("Bessie's eyes are good\n");
    }
    return 0;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值