POJ 2492 并查集 注释版

源自:http://blog.csdn.net/tsaid/article/details/6679548

题意:调查一种虫子的性行为,先假定虫子里没有同性恋。每一次测试输入N只虫,然后输入M个数对( x, y ),表示 x, y 之间有性行为, 最后判断假设成立与否(即判断有没有同性恋)。这道题目有点邪恶。

#include <iostream>
using namespace std;

#define N 1000005
int opp[N], father[N], rank[N];
//opp记录那个他/她
void make_set ( int x )
{
	for ( int i = 0; i <= x; ++i )
	{
		father[i] = i;
		opp[i] = rank[i] = 0;
	}
}

int find_set ( int x )
{
	if ( father[x] != x )
		father[x] = find_set(father[x]);
	return father[x];
}

void Union ( int x, int y )
{
	int fx = find_set(x);
	int fy = find_set(y);
	if ( fx == fy ) return;
	if ( rank[fx] > rank[fy] )
		father[fy] = fx;
	else
		father[fx] = fy;
	if ( rank[fx] == rank[fy] )
		rank[fy]++;
}

int main()
{
	int t, n, m, x, y;
	bool find;
	scanf("%d",&t);
	for ( int i = 1; i <= t; ++i )
	{
		find = false;
		scanf("%d%d",&n,&m);
		make_set(n);
		while ( m-- )
		{
			scanf("%d%d",&x,&y);
			if ( find == false )
			{
				if ( opp[x] == 0 && opp[y] == 0 )
				{//如果x与y之前都没发生过性行为的话,然后x与y发生了,分别记录对方
					opp[x] = y;
					opp[y] = x;
				}
				else if ( opp[x] != 0 && opp[y] == 0 )
				{//如果x不是初的话,但是y是初,
					opp[y] = x;//记录对方
					Union(y,opp[x]);//y与opp[x]应该是同一个性别,合并
				}
				else if ( opp[x] == 0 && opp[y] != 0 )
				{//与上同理
					opp[x] = y;
					Union(x,opp[y]);
				}
				else if ( opp[x] != 0 && opp[y] != 0 )
				{
					if ( find_set(x) == find_set(y) )//当两个集合里面都有一样的虫子,那么就表示有同性恋
						find = true;
					Union(x,opp[y]);
					Union(y,opp[x]);
				}
			}
		}
		printf("Scenario #%d:\n",i);
		if ( find )
			printf("Suspicious bugs found!\n");
		else
			printf("No suspicious bugs found!\n");
		if ( i != t ) putchar('\n');
	}
	return 0;
}




你可能感兴趣的:(POJ 2492 并查集 注释版)