POJ1308 Is It A Tree? (easy but...)

 

 Description
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. 
POJ1308 Is It A Tree? (easy but...)

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. 

题目大意:给定一些点和边的关系,然后判断是否是一棵树(注意:森林是不可以的!!!)

思路:读入边的信息,然后将两个点合并,将后面点的fa给前面的点, 如两点已经在同一集合就不是树,最后判断是否是森林就可以了。。。

code:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int fa[100001]={0};
int visit[100001]={false},visitt[100001]={false};
int rool(int x)
{
if (fa[x]!=x) fa[x]=rool(fa[x]);
return fa[x];
}
int main()
{
int a,b,r1,r2,ci=0,i,t,maxn;
bool f=false;
while (cin>>a>>b)
{
++ci;
f=false;
if (a==-1&&b==-1) break;
for (i=0;i<=100000;++i)
  fa[i]=i;
memset(visit,false,sizeof(visit));
memset(visitt,false,sizeof(visitt));
t=maxn=0;
while (a!=0||b!=0)
{
if (a>maxn) maxn=a;
if (b>maxn) maxn=b;
visit[a]=visit[b]=true;
r1=rool(a);
r2=rool(b);
if (r1==r2) 
  f=true;
fa[r2]=r1;
cin>>a>>b; 
}
if (!f)
{
for (i=1;i<=maxn;++i)
  if (visit[i])
  {
   r1=rool(i);
   if (!visitt[r1])
   {
   visitt[r1]=true;
   ++t;
   }
  }
if (t>1) f=true;
    }
cout<<"Case "<<ci<<" is ";
if (f) cout<<"not ";
cout<<"a tree."<<endl;
}

 

你可能感兴趣的:(tree)