93-臭虫也疯狂

                   臭虫也疯狂
霍普教授研究臭虫的性取向。实验前他弄清楚了n个臭虫的性别,并在臭虫的背上标了数
字编号(1~n)。现在给一批臭虫的编号配对,要检查里面有没有同性恋。
输入描述
第一行是整数c,下面接着有c个测试用例。
每个测试用例的第一行是臭虫的数目n(12000),以及配对的数目m(110^6)。接下来
的行就是m个配对的臭虫编号.
输出描述
一共c行, 每行打印“testcase i:没发现同性恋”,或者“testcase i:发现同性恋”
输入样例
2
3 3
1 2
2 3
1 3
4 2
1 2
3 4

输出样例
testcase 1:发现同性恋
testcase 2:没有发现同性恋

思路:可坑了我好久的时间, 并查集的简单应用应该是,但还是绕进去了, 并查集应使得同性之间成为一个群体, 故应多开一个数组存储其对象, 最后还不能用cin, cout, 改为c的才堪堪过了校oj;

并查集要压缩。
 

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int n, m;
const int MAX = 100005;
int pre[MAX];
int c[MAX];
 
int find(int x){
	if(pre[x] == x){
		return x;
	}
	return pre[x] = find(pre[x]);
}

void unit(int x, int y){
	pre[find(x)] = find(y);
}

int init(){
	for(int i = 1; i <= n; i++){
		pre[i] = i;
	}
	memset(c, 0, sizeof(c));
}
 
int main(){
 	int t;
 	cin >> t;
 	for(int k = 1; k <= t; k++){
// 		cin >> n >> m;
 		scanf("%d%d", &n, &m);
 		init();
 		int flag = 1;
 		for(int i = 0; i < m; i++){
 			int a, b;
 			scanf("%d %d", &a, &b);
 			if(c[a] == 0 && c[b] == 0){
 				c[a] = b;
 				c[b] = a;
 			}
 			else if(c[a] && c[b] == 0){
 				unit(c[a], b);
 				c[b] = a;
 			}
 			else if(c[a] == 0 && c[b]){
 				unit(a, c[b]);
 				c[a] = b;
 			}
 			else{
 				unit(a, c[b]);
 				unit(b, c[a]);
 			}
 			if(find(a) == find(b)){
 				flag = 0;
// 				break;
 			}
 		}
 		if(flag == 0){
 			printf("testcase %d:发现同性恋
", t);
		}
		else{
			printf("testcase %d:没有发现同性恋
", t);
		}
 	}
 
	return 0;
}

  

原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/10858608.html