Description
给出一些几点的连接情况,判断这些节点能否组成一棵树
Input
多组用例,每组用例每次输入两个整数a和b表示有一条a指向b的边,以0 0结束一组用例的输入,以-1 -1结束所有输入
Output
对于每组用例,判断这些节点能否组成一棵树
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 -1
Sample Output
Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree.
Solution
简单并查集,不知道输入节点的编号所以先开一个标记数组标记每个编号的节点是否出现过,然后注意几种特殊情况
1.(0 0) 空树是一棵树
2.1 1 0 0 自己指向自己,不是树
3.1 2 2 1 0 0 儿子指向父亲,不是树
4.1 2 1 2 0 0 重边,不是树
5.1 2 4 5 0 0 森林,不是树
Code
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
#define maxn 111
int par[maxn];
int mark[maxn];
void init(int n)
{
for(int i=0;i<n;i++)
{
par[i]=i;
mark[i]=0;
}
}
int find(int x)
{
if(par[x]==x) return x;
return par[x]=find(par[x]);
}
void unite(int x,int y)
{
x=find(x);
y=find(y);
if(x==y) return;
par[y]=x;
}
int main()
{
int x,y,root,res=1;
while(~scanf("%d%d",&x,&y),~x)
{
if(x==0&&y==0)
{
printf("Case %d is a tree.\n",res++);
continue;
}
bool flag=1;
init(maxn);
mark[x]=mark[y]=1;
root=x;
if(x==y)flag=0;
else unite(x,y);
while(scanf("%d%d",&x,&y),x||y)
{
mark[x]=mark[y]=1;
if(find(x)==find(y))flag=0;
else unite(x,y);
}
for(int i=1;i<maxn;i++)
if(mark[i]&&find(i)!=find(root))
{
flag=0;
break;
}
if(flag)printf("Case %d is a tree.\n",res++);
else printf("Case %d is not a tree.\n",res++);
}
return 0;
}