poj_1182_食物链(并查集)

本文介绍了一个关于并查集的经典应用案例,通过秩的概念来处理不同动物之间的关系问题。使用秩来表示动物间的捕食关系,并通过并查集的数据结构进行有效管理。文章提供了完整的代码实现,有助于读者深入理解并查集的应用。

题型:并查集


题意:中文题,不解释~


分析:

       典型的并查集应用。

       rank中存的秩为0、1、2,分别表示0吃1,1吃2,2吃0。

       将同种动物归于一个集合,查找判断是否为假话。


代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#define MAXN 50050
using namespace std;
int father[MAXN];//father[x]表示x的父节点
int rank[MAXN];//rank[x]表示x的秩
void Make_Set(int x) { //初始化
    father[x] = x;
    rank[x] = 0;
}
int Find_Set(int x) {
    int tmp = father[x];
    if(x != father[x]) {
        father[x] = Find_Set(father[x]);
        rank[x] = (rank[x] + rank[tmp]) % 3;
    }
    return father[x];
}

void Union(int x,int y,int w) {
    int a = Find_Set(x);
    int b = Find_Set(y);
    father[b] = a;
    rank[b] = (rank[x] - rank[y] + w + 3) % 3;
}


int main() {
    int n,m,num,x,y;
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++) {
        Make_Set(i);
    }
    int ans = 0;
    while(m--) {
        scanf("%d%d%d",&num,&x,&y);
        if(x>n || y>n) {
            ans++;
        } else {
            if(num == 1) {
                if(Find_Set(x) == Find_Set(y) && rank[x] != rank[y])
                    ans++;
                else Union(x,y,0);
            } else {
                if(Find_Set(x) == Find_Set(y) && (rank[x]+1)%3 != rank[y])
                    ans++;
                else Union(x,y,1);
            }
        }
    }
    printf("%d\n",ans);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值