Visitors hit counter dreamweaver

POJ 1308 Is it a tree(并查集)

POJ1308

并查集的学习

#include <iostream>
#include <memory.h>
using namespace std;

int father[5000];
bool has_point[5000];
int case_number;

void Ini_Set(int y){
father[y]=y;
has_point[y]=true;
}

int Find_Set(int x){
if(father[x]!=x){ //不是单独的节点
father[x]=Find_Set(father[x]);
}
return father[x];
}
void Union(int x,int y){ //s point to y
x=Find_Set(x);
y=Find_Set(y);
father[y]=x;
}

int MaxOf(const int x,const int y){
return x>y?x:y;
}

int Begin(){

int s,t,max=0;
bool finish=false;
while(cin>>s>>t){
if(s>0 && t>0){
Ini_Set(s);
Ini_Set(t);
max=MaxOf(MaxOf(max,s),t); //找出节点值最大的点,注意用法
if(Find_Set(s)!=Find_Set(t))
Union(s,t);
else{ //存在重复路径
cout<<"Case "<<case_number<<" is not a tree."<<endl;
finish=true;
break;
}
}
else{
if(s==-1 && t==-1){
return 1;
}
break;
}
}
if(!finish){
int f=Find_Set(max);
for(int i=1;i<=max;++i)
if(has_point[i] && Find_Set(i)!=f){ //是森林
cout<<"Case "<<case_number<<" is not a tree."<<endl;
finish=true;
break;
}
}
if(!finish)
cout<<"Case "<<case_number<<" is a tree."<<endl;
return 0;
}

int main(){
while(true){
++case_number;
if(Begin())
return 0;
}
return 0;
}

 

posted @ 2011-12-14 10:28  Jason Damon  阅读(330)  评论(0编辑  收藏  举报