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.Input
The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes Each edge description will consist of a pair of integers; the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero.
Output
For each test case display the line "Case k is a tree." or the line "Case k is not a tree.", where k corresponds to the test case number (they are sequentially numbered starting with 1).
Sample Input
6 8 5 3 5 2 6 4 5 6 0 0 8 1 7 3 6 2 8 9 7 5 7 4 7 8 7 6 0 0 3 8 6 8 6 4 5 3 5 6 5 2 0 0 -1 -1Sample Output
Case 1 is a tree. Case 2 is a tree. Case 3 is not a tree.题意:给出许多对数字a和b,表示a到b之间有一条边,判断图是否为一棵树。
分析:判断为一棵树,无环,只有一个根节点,用并查集把俩个点合并,合并之前判断是否已经在同一并查集内,否则有环,还要判断根节点的个数,如果单独输入0 0也是一种情况,也是一棵树。
代码:
#include<stdio.h> #include<string.h> #include<algorithm> #define N 100 using namespace std; int f[N]; int n,x,y; int flag=0,cout=0; int book[N]; void init() { for(int i=1; i<N; i++) f[i]=i; memset(book,0,sizeof(book)); } int getf(int x) { if(x==f[x]) return x; return f[x]=getf(f[x]); } void merge(int x,int y) { x=getf(x); y=getf(y); if(x!=y) f[y]=x; } int main() { int t=0; while(1) { cout=1; t++; init(); //初始化 while(~scanf("%d%d",&x,&y)&&x!=0&&y!=0) { if(x==-1&&y==-1) { flag=1; break; } if(getf(x)==getf(y)) cout=0; //判断是否有环 merge(x,y); //并查集 book[x]=book[y]=1; //标记 } if(flag==1) break; int sum=0; for(int i=1; i<N; i++) { if(f[i]==i&&book[i]==1) //判断根节点的个数 sum++; } if(sum!=1&&sum!=0) //多节点和有环 不是一棵树 cout=0; if(cout) printf("Case %d is a tree.\n",t); else printf("Case %d is not a tree.\n",t); } return 0; }
POJ - 1308 E - Is It A Tree?
最新推荐文章于 2020-04-12 19:01:12 发布