http://poj.org/problem?id=1308
无环
cnt=1
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <string>
#include <iostream>
#include <stack>
#include <queue>
#include <vector>
#include <algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
#define N 500+20
#define M 30000+20
#define MOD 1000000000+7
#define inf 0x3f3f3f3f
using namespace std;
int f[M],vis[M],n,m,flag;
void init()
{
flag=0;
for(int i=1; i<=M; i++)
f[i]=i,vis[i]=0;
}
int find(int x)
{
if(x==f[x])
return x;
else
{
f[x]=find(f[x]);
return f[x];
}
}
void mix(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
f[fy]=fx;
else
flag=1;//第一个判断条件
}
int main()
{
int x,y,k=1;
while(~scanf("%d%d",&x,&y))
{
if(x<0&&y<0)
return 0;
if(!x||!y)//空树也是树
{
printf("Case %d is a tree.\n",k++);
continue;
}
init();//初始化并查集
mix(x,y);//把x,y加入并查集
vis[x]=1,vis[y]=1;
int a,b;
while(1)
{
scanf("%d%d",&a,&b);
if(a==0&&b==0)
break;
mix(a,b);
vis[a]=1,vis[b]=1;
}
int cnt=0;
//判断是否只有一个根节点
for(int i=1; i<=M; i++)
if(vis[i]&&find(i)==i)
cnt++;//第二个条件
if(cnt>1)
flag=1;
if(flag)
printf("Case %d is not a tree.\n",k++);
else
printf("Case %d is a tree.\n",k++);
}
}
//错误代码,输入有问题
#include<iostream>
#include<math.h>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int pre[50000];
int find(int x)
{
return x==pre[x]?x:pre[x]=find(pre[x]);
//return
}
void unions(int x,int y)
{
int fx=find(x);
int fy=find(y);
if(fx!=fy)
{
pre[fy]=fx;//有方向要基准
}
}//并查集方法;
void init()
{
for(int i=1; i<=100000; i++)
{
pre[i]=i;
}
}
int ss[100000];
int main()
{
//输入不对
bool marks[50000]={0};
int ru[100000]={0};
int u,v;
int t=0;
int n=0;
int gen;
int num=0;
int t1=0;
init();
int kk=0;
int flag;
while(cin>>u>>v)
{
//cout<<marks[u]<<"fsdf"<<endl;
//cout<<"n"<<n<<endl;
if(u==-1)break;
if(u==0&&flag==0||(n==0&&u==0)){cout<<"Case "<<++t<<" is a tree."<<endl;continue;}
if(u==0)
{
//cout<<n<<endl;
//cout<<"sd"<<endl;
if(n==1){cout<<"Case "<<++t<<" is a tree."<<endl;continue;}
for(int i=1; i<=3000; i++)
{
//cout<<find(pre[ss[i]])<<endl;
if(marks[i]&&find(pre[i])==i&&ru[i]==0)
{
gen=i;
++num;
cout<<gen<<endl;
}
}
if(num==1)
{
for(int i=1; i<=3000; i++)
{
if(i!=gen&&ru[i]==1&&marks[i])
{
++t1;
}
}
if(t1==n-1)
{
cout<<"Case "<<++t<<" is a tree."<<endl;
}
else
{
cout<<"Case "<<++t<<" is not a tree."<<endl;
}
}
else
{
cout<<"Case "<<++t<<" is not a tree."<<endl;
}
n=0;
num=0;
t1=0;
init();
memset(ru,0,sizeof(ru));
memset(marks,0,sizeof(marks));
memset(ss,0,sizeof(ss));
}
else
{
unions(u,v);
// cout<<n<<endl;
//cout<<" ddddd"<<marks[u]<<endl;
if(marks[u]==0)
{
++n;
marks[u]=1;
ss[n]=u;
// cout<<n<<endl;
}
if(marks[v]==0)
{
++n;
marks[v]=1;
ss[n]=v;
}
ru[v]++;
//cout<<"ru[v]"<<ru[v]<<" "<<v<<endl;
}
flag=v;
}
return 0;
}