题目1481:Is It A Tree?

A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of one or more nodes connected by directed edges between nodes satisfying the following properties.

There is exactly one node, called the root, to which no directed edges point. 
Every node except the root has exactly one edge pointing to it. 
There is a unique sequence of directed edges from the root to each node. 
For example, consider the illustrations below, in which nodes are represented by circles and edges are represented by lines with arrowheads. The first two of these are trees, but the last is not.


In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not.

注意空树的情况,wa了好几次,不认真审题的后果。。。

(1)判定节点的入度,只能为0或者1;//排除上图的第三种情况

(2)入度为0的节点只有一个;

(3)既然是一棵树,必须是有向无换图,由拓扑排序思想解之。

注意到入度为0的节点只有一个,所以可保证联通分量的唯一性。

由此开始coding。。。。。。

// 题目3:Is It A Tree.cpp: 主项目文件。

//#include "stdafx.h"
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

const int N=10003;
int degrees[N];
int used[N];
vector<int> ivec1[N];
queue<int> Q;
int n;

void init()
{
	n=0;
	memset(used,0,sizeof(used));
	for(int i=0;i<N;i++)
	{
		degrees[i]=0;
		ivec1[i].clear();
	}
}

bool isTree()
{
	while(!Q.empty())
		Q.pop();
	for(int i=0;i<N;i++)
	{
		if(used[i])
		{
			if(degrees[i]==0)
				Q.push(i);
			else if(degrees[i]>1)
				return false;//树的入度只允许为1
		}		
	}
	if(Q.size()>1)//树的根只有一个
		return false;
	int cnt=0;
	while(!Q.empty())
	{
		int temp=Q.front();
		Q.pop();
		cnt++;
		for(vector<int>::iterator ite=ivec1[temp].begin();ite!=ivec1[temp].end();ite++)
		{
			degrees[*ite]--;
			if(degrees[*ite]==0)
				Q.push(*ite);
		}
	}
	if(cnt==n)
		return true;
	else
		return false;
}

int main()
{
	int from,to;
	int caseCnt=1;
	while(~scanf("%d%d",&from,&to))
	{
		if(from==0&&to==0)
		{
			printf("Case %d is a tree.\n",caseCnt++);
			continue;
		}
		if(from<0&&to<0)
			break;
		init();
		degrees[to]++;
		ivec1[from].push_back(to);
		if(!used[from])
		{
			used[from]=true;
			n++;
		}
		if(!used[to])
		{
			used[to]=true;
			n++;
		}
		while(scanf("%d%d",&from,&to))
		{
			if(from==0&&to==0)
				break;
			degrees[to]++;
			ivec1[from].push_back(to);
			if(!used[from])
			{
				used[from]=true;
				n++;
			}
			if(!used[to])
			{
				used[to]=true;
				n++;
			}
		}
		bool flag=isTree();
		if(flag)
			printf("Case %d is a tree.\n",caseCnt++);
		else
			printf("Case %d is not a tree.\n",caseCnt++);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值