题目1481:Is It A Tree?

来源:互联网 发布:ubuntu查看gpu使用率 编辑:程序博客网 时间:2024/06/11 22:04

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;elsereturn 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++);elseprintf("Case %d is not a tree.\n",caseCnt++);}return 0;}


原创粉丝点击