http://acm.hdu.edu.cn/showproblem.php?pid=1325
跟小希的迷宫那一题题意差不多,只不过那个是无向图,这个是有向图。那么区别在于这个题在输入边的时候不能指向自身,并且有父亲就不可以接另外的父亲了。
其他的都是一样。
#include<cstdio>
#include<cstring>
#define N 100001
int father[N],mark[N],flag,edges;
int find(int x)
{
if(x==father[x]) return x;
father[x]=find(father[x]);
return father[x];
}
void Union(int x,int y)
{
int a=find(x);
int b=find(y);
if(a==b)
{
flag=1;
return;
}
mark[a]=1;
mark[b]=1;
edges++;
father[b]=a;
}
int main()
{
//freopen("a.txt","r",stdin);
int a,b,c,d,i,m,cas=1;
while(1)
{
scanf("%d%d",&a,&b);
if(a<0&&b<0)break;
if(a==0&&b==0) {printf("Case %d is a tree.\n",cas++);continue;}
flag=edges=m=0;
memset(mark,0,sizeof(mark));
for(i=1;i<=N;i++)
father[i]=i;
Union(a,b);
while(scanf("%d%d",&c,&d)!=EOF)
{
if(c==0&&d==0)break;
if(c==d||father[d]!=d) flag=1; //注意这里,不能指向自身,只能有一个父亲。
Union(c,d);
}
if(flag) {printf("Case %d is not a tree.\n",cas++);continue;}
for(i=1;i<=N;i++)
{
if(mark[i]) m++;
}
//printf("%d %d\n",m,edges);
if(m==edges+1)
{
printf("Case %d is a tree.\n",cas++);
}
else printf("Case %d is not a tree.\n",cas++);
}
return 0;
}