题解 | Is It A Tree?

#include<iostream>

using namespace std;
const int maxn = 10005;
int ind[maxn];
bool visit[maxn];
int f[maxn];
int find(int x){
	if(x!=f[x])return find(f[x]);
	else return f[x];
}
void init(){
	for(int i=0;i<maxn;i++){
		f[i] = i;
		visit[i] = false;
	}
}
int main(){
	int from,to;
	int k = 1;
	while(cin>>from>>to){
		if(from==-1 && to==-1)break;
		if(from==0 && to==0){
			printf("Case %d is a tree.\n",k++);
			continue;
		}
		int maxd = max(from,to);
		init();
		bool istrue = true;
		f[to] = from;
		visit[to] = true,visit[from] = true;
		if(from==to)istrue = false;
		while(cin>>from>>to){
			if(from==0 & to==0)break;
			if(f[to]!=to)istrue = false;
			else f[to] = from;
			if(from==to)istrue = false;
			visit[to] = true,visit[from] = true;
			maxd = max(maxd,from);
			maxd = max(maxd,to);
		}
		int indrgee = 0;
		for(int i=0;i<=maxd;i++){
			if(!visit[i])continue;
			if(f[i]==i)indrgee++;
		}
		if(indrgee!=1)istrue = false;
		if(istrue){
			printf("Case %d is a tree.\n",k);
		}else{
			printf("Case %d is not a tree.\n",k);
		}
		k++;
	}
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务