POJ 2492 A Bug's Life (并查集)

有一些昆虫,给出若干它们的配对关系,判断其中是否有虫子搞基。

一开始也是想到并查集,但是没有想到怎么实现,后来参考了一下人家的做法。

精髓是要设一组变量,标记每只虫子的第一个对象。边读取数据,边更新这组变量和并查集,直到找到基佬就OK。

#include<iostream>
#include<cstdio>
using namespace std;

typedef struct{
	int father;
	int com;
} NODE;

NODE bug[2200];

void init(int x){
	for(int i = 1; i <= x; i++){
		bug[i].father = i;
		bug[i].com = -1;
	}
}

int find(int x){
	if(x == bug[x].father)
		return x;
	else
		return bug[x].father = find(bug[x].father);
}

void join(int x, int y){
	int r1 = find(x);
	int r2 = find(y);
	bug[r1].father = r2;
}

int main(){
	int T, caseNo = 0;
	scanf("%d", &T);
	while(T--){
		int n, m;
		scanf("%d %d", &n, &m);
		init(n);
		bool found = false;
		while(m--){
			int x, y;
			scanf("%d %d", &x, &y);
			if(found)
				continue;
			if(bug[x].com == -1){
				if(bug[y].com == -1){
					bug[x].com = y;
					bug[y].com = x;
				}else{
					join(x, bug[y].com);
					bug[x].com = y;
				}
			}else{
				if(bug[y].com == -1){
					join(bug[x].com, y);
					bug[y].com = x;
				}else{
					if(find(x) == find(y))
						found = true;
					else{
						join(bug[x].com, y);
						join(bug[y].com, x);
					}
				}
			}
		}
		printf("Scenario #%d:\n", ++caseNo);
		if(found)
			printf("Suspicious bugs found!\n");
		else
			printf("No suspicious bugs found!\n");
		if(T != 0)
			printf("\n");
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值