poj 1182 食物链 带权并査集

题目链接:   http://poj.org/problem?id=1182


这个题需要将动物分成3种,每次以y=0为对象,吃他的x为1,,需要注意的是下一次碰到x cha函数递归更新与x有关的对象


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define N 50005
int father[N],num[N];

int cha(int x)
{
    if(x!=father[x])
    {
        int t=father[x];
        father[x]=cha(father[x]);
        num[x]=(num[x]+num[t])%3;
    }
    return father[x];
}
int main()
{
    int n,m,i;
    scanf("%d%d",&n,&m);
        int ans=0;
        for(i=0;i<=n;i++)
        {
            father[i]=i;
            num[i]=0;
        }
        int x,y,len;
        while(m--)
        {
            scanf("%d%d%d",&len,&x,&y);
            if(x>n||y>n)
            {
                ans++;
                continue;
            }
            if(x==y&&len==2)
            {
                 ans++;
                continue;
            }
            int xx=cha(x);
            int yy=cha(y);
            if(xx!=yy)
            {
                father[xx]=yy;
                num[xx]=(-num[x]+num[y]+len-1+3)%3;
            }
            else
            {
                if(num[xx]!=(-num[x]+num[y]+len-1+3)%3)
                    ans++;
            }
        }
        printf("%d\n",ans);
    return 0;
}

因为以以y为对象,题目说输入2时,代表x吃y,而我们规定吃y的权为1,所以要2-1=1;

其实最重要的是那个cha函数,仔细体会吧,我也是看别人的才想通的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值