杭电ACM1272(并查集)

#include 
using namespace std;

#define MAXN 100001

int father[ MAXN ];
int visited[ MAXN ];
bool flag;

void init()
{
	for(int i = 0; i < MAXN; i ++)
	{
		father[ i ] = i;
		visited[ i ] = 0;
	}
	flag = true;
}

int find(int s)
{
	int t = s;
	while(t != father[ t ])
	{
		t = father[ t ];
	}
	
	while(s != father[ s ])
	{
		father[ s ] = t;
		s = father[ s ];
	}
	return t;
}

void merge(int a, int b)
{
	int fa = find(a);
	int fb = find(b);
	if(fa == fb)
	{
		flag = false;
		return;		
	}	
	else
	{
		father[ fb ] = fa;
	}
	
}

int main()
{
	int a, b;
	
	init();
	while(cin>>a>>b)
	{
		if(a == -1 && b == -1)
		{
			break;
		}
		if(a == 0 && b == 0)
		{
			int cnt = 0;
			for(int i = 0; i < MAXN; i ++)
			{
				if(visited[ i ] == 1 && father[ i ] == i)
				{
					cnt ++;
				}
			}
			if(cnt == 0)
			{
				printf("Yes\n");
			}
			else if(flag && cnt == 1)
			{
				printf("Yes\n");
			}
			else
			{
				printf("No\n");
			}
			init();
		}
		else
		{
			merge(a, b);
			visited[ a ] = 1;
			visited[ b ] = 1;
		}
	}
	return 0;
}

你可能感兴趣的:(杭电ACM1272(并查集))