【N - Is It A Tree?】

思路:

//0ms		1200kB


#include <iostream>
#include <cstring>
#include <cstdio>

using namespace std;

const int maxn = 1e5 + 5;

int T = 0;
bool ans;
int par[maxn];
bool app[maxn];

void INIT(){
	ans = true;
	memset(par , -1 , sizeof(par));
	memset(app , 0 , sizeof(app));
	return ;
}

int FIND(int i){
	return par[i] == -1 ? i : par[i] = FIND(par[i]);
}

void UNION(int l,int r){
	par[r] = l;
	return ;
}

int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	int l,r;
	while(cin>>l>>r && l!=-1){
		INIT();
		while(true){
			if(!l)
				break;
			app[l] = app[r] = true;
			int parl = FIND(l);
			int parr = FIND(r);
			if(parr != r || parl == parr)
				//r既不是树根也不是新点;r是树根时l是叶子 
				ans = false;
			else
				UNION(parl , parr);
			cin>>l>>r;
		}
		int cnt = 0;
		for(int i=0;i<maxn;i++)
			if(app[i] && FIND(i) == i)
				++cnt;
		if(cnt > 1)
			ans = false;
		if(ans)
			printf("Case %d is a tree.\n" , ++T);
		else
			printf("Case %d is not a tree.\n" , ++T);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/flash403/article/details/94726951