题型:并查集
题意:中文题,不解释~
分析:
典型的并查集应用。
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;
}
本文介绍了一个关于并查集的经典应用案例,通过秩的概念来处理不同动物之间的关系问题。使用秩来表示动物间的捕食关系,并通过并查集的数据结构进行有效管理。文章提供了完整的代码实现,有助于读者深入理解并查集的应用。

2万+

被折叠的 条评论
为什么被折叠?



