1. 程式人生 > >POJ 2492 並查集

POJ 2492 並查集

題意:調查一種蟲子的性行為,先假定蟲子裡沒有同性戀。每一次測試輸入N只蟲,然後輸入M個數對( x, y ),表示 x, y 之間有性行為, 最後判斷假設成立與否(即判斷有沒有同性戀)。

#include <iostream>
using namespace std;

#define N 1000005
int opp[N], father[N], rank[N];

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 )
				{
					opp[x] = y;
					opp[y] = x;
				}
				else if ( opp[x] != 0 && opp[y] == 0 )
				{
					opp[y] = x;
					Union(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;
}