BIT1060 Is It A Tree?

题意

树的数据结构定义为

根节点没有一条边指向它 

除根节点外每个节点必有刚好一条边指向它 

从根节点刚好只有一条路径可以到达每个点

样例有多组,每组样例以0 0结尾

如果样例是-1 -1,程序终止

每组样例的输入是n对数,一对数a和b代表a到b有一条有向边

解法:

原来想怎么解来着忘了,反正弄了一堆很麻烦的玩意还RE了

后来用

入度为0的点只有一个,其余都是入度为1的点这个性质过了

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
int counter[1010];//每个点的入度
bool exist[1010];//在此组样例中出现的点
int main()
{
	int a,b;
	int kk=1;
	while(scanf("%d %d",&a,&b))
	{
		if(a==0&&b==0)
		{
			printf("Case %d is a tree.\n",kk++);
		}
		if(a==-1&&b==-1)
		{
			break;
		}
		memset(counter,0,sizeof(counter));
		memset(exist,false,sizeof(exist));
		counter[b]++;
		exist[a]=true;
		exist[b]=true;
		while(scanf("%d %d",&a,&b),a||b)
		{
			counter[b]++;
			exist[a]=true;
			exist[b]=true;
		}
		bool ans=true;
		int num=0;//出现过的且入度为0的点
		for(int i=1;i<=1000;i++)//所有点的入度应为0或1
		{
			if(counter[i]>1)
			{
				ans=false;
			}
			if(counter[i]==0&&exist[i])
			{
				num++;
			}
		}
		if(num!=1)
		{
			ans=false;
		}
		if(ans)
		{
			printf("Case %d is a tree.\n",kk++);
		}
		else
		{
			printf("Case %d is not a tree.\n",kk++);
		}
	}
	return 0;
}



你可能感兴趣的:(BIT1060 Is It A Tree?)