题目链接:http://poj.org/problem?id=1308
题意:x, y 表示x 与 y连接,给出一波这样的数据,问这组数据能否构成树,即不能形成回路,不能有多个根节点;要注意可以是空树;
代码:
#include <iostream>
#include <stdio.h>
#define MAXN 1000000
using namespace std; int pre[MAXN], flag; int find(int x){
int r=x;
while(pre[r]!=r){
r=pre[r];
}
int i=x;
while(i!=r){
int gg=pre[i];
pre[i]=r;
i=gg;
}
return r;
} int jion(int x, int y){
int xx=find(x);
int yy=find(y);
if(xx!=yy){
pre[xx]=yy;
}else{
flag=;
}
} int main(void){
int a, b, t=;
while(scanf("%d%d", &a, &b)&&(a!=-&&b!=-)){
if(!a&&!b){
printf("Case %d is a tree.\n", t++);
}else{
flag=;
int Max=, c[MAXN], d[MAXN], i=;
Max=max(Max, max(a, b));
c[]=a, d[]=b;
int x, y;
while(scanf("%d%d", &x, &y)&&x&&y){
c[i]=x;
d[i]=y;
Max=max(Max, max(x, y));
i++;
}
for(int j=; j<=Max; j++){
pre[j]=j;
}
for(int j=; j<i; j++){
jion(c[j], d[j]);
}
int ans=;
for(int j=; j<i; j++){
if(c[j]==pre[c[j]]){
ans++;
}else if(d[j]==pre[d[j]]){
ans++;
}
}
if(ans> || flag==){
printf("Case %d is not a tree.\n", t++);
}else{
printf("Case %d is a tree.\n", t++);
}
}
}
return ;
}