POJ - 1182 食物链 带权并查集

题意:

中文不解释

分析:

每个节点包括两部分,关系域跟节点域,节点域更新跟普通并查集一样,关系域借助向量进行更新。

讲解的很好的博客:https://blog.csdn.net/niushuai666/article/details/6981689

#include<cstdio>

using namespace std;

const int maxn=5e4+10;

struct Node{
    int pre;
    int relation;       //   p[x].pre与x的关系    0 同类   1  x->y    2 y->x
}p[maxn];

int find(int x){
    if(p[x].pre==x) return x;
    int tmp=p[x].pre;
    p[x].pre=find(tmp);
    p[x].relation=(p[x].relation+p[tmp].relation)%3;
    return p[x].pre;
}

int main(){

    int n,k;
    int op,a,b;
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++){
        p[i].pre=i;
        p[i].relation=0;
    }
    int ans=0;
    while(k--){
        scanf("%d%d%d",&op,&a,&b);
        if(a>n||b>n){
            ans++;
            continue;
        }
        if(op==2&&a==b){
            ans++;
            continue;
        }
        int root1=find(a);
        int root2=find(b);
        if(root1!=root2){
            p[root2].pre=root1;
            p[root2].relation=(p[a].relation+op-1-p[b].relation+3)%3;
        }else{
            if(op==1&&(p[a].relation!=p[b].relation)){
                ans++;
                continue;
            }else if(op==2&&(-p[a].relation+p[b].relation+3)%3!=op-1){
                ans++;
                continue;
            }
        }
    }
    printf("%d\n",ans);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值