小希的迷宫
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 18880 Accepted Submission(s): 5738
整个文件以两个-1结尾。
#include <iostream>
using namespace std;
int father[111111],chuxian[111111],k,rank[111111];
int Find(int a) //找出祖先
{
while(a!=father[a])a=father[a]; //不用那种递归方式是避免堆栈段溢出
return a;
}
void Union(int a,int b) //连通a,b两点
{
a=Find(a),b=Find(b);
if(a!=b)father[a]=b;
else k=0;
}
int main (void)
{
int a,b,i,j,l,max,min;
while(cin>>a>>b&&(a!=-1||b!=-1))
{
if(a==0&&b==0){cout<<"Yes"<<endl;continue;}
if(a==b){cout<<"No"<<endl;continue;}
k=1;
for(i=0;i<111111;i++)father[i]=i,chuxian[i]=0; //初始化
Union(a,b);
chuxian[a]=chuxian[b]=1;
while(cin>>a>>b&&(a!=0||b!=0))
{
chuxian[a]=chuxian[b]=1; //把出现过的点记录下来
Union(a,b); //连通a,b两点
}
for(i=1,j=0;i<=100000;i++)
{
if(chuxian[i]&&father[i]==i)j++; //记录即出现过又是祖先的点的个数
if(j==2){k=0;break;} //当存在1个以上家族的时候就可以输出No了
}
if(k)cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}