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.
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.
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 -1
Case 1 is a tree. Case 2 is a tree.Case 3 is not a tree.
解题思路:这道题和那个小希的迷宫差不多,主要是让你判断是否能组成一个树。
主要判断依据是:不能有环,每个结点的入度不能大于1(根结点为0),只能有有个根结点;
这道题用并查集的方法做。
#include<iostream> #include<algorithm> #include<cstring> using namespace std; int const maxn=1000; int pre[maxn]; int mark[maxn]; int du[maxn]; int sign,num,step=1; int x,y; int find(int x) { if(x==pre[x]) return x; else return pre[x]=find(pre[x]); } void join(int x,int y) { int m,n; m=find(x); n=find(y); if(m!=n) { pre[m]=n; } } int main() { while(cin>>x>>y) { memset(pre,0,sizeof(pre)); memset(mark,0,sizeof(mark)); memset(du,0,sizeof(du)); for(int i=0;i<maxn;i++) { pre[i]=i; mark[i]=0; } sign=0; if(x<0&&y<0) break; if(x==0&&y==0) { cout<<"Case "<<step++<<" is a tree."<<endl; continue; } if(find(x)==find(y)) { sign=1; } join(x,y); du[y]++; mark[x]=1,mark[y]=1; while(cin>>x>>y&&x&&y) { if(find(x)==find(y)) { sign=1; } join(x,y); du[y]++; mark[x]=1,mark[y]=1; } num=0; for(int i=0;i<maxn;i++) { if(mark[i]==1&&pre[i]==i) num++; if(du[i]>1) sign=1; } if(num>1||sign==1) cout<<"Case "<<step++<<" is not a tree."<<endl; else cout<<"Case "<<step++<<" is a tree."<<endl; } return 0; }