Time Limit: 1000MS | Memory Limit: 32768KB | 64bit IO Format: %I64d & %I64u |
Description

Input
整个文件以两个-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
Yes Yes No
Source
1。 判断成环的时候,只要判断输入边的两个点。有一个共同的父节点,那么这两个点就成环。
2。判断连通的时候,只要判断根节点数为1即可。
注意:当输入的这组数据只有 0 0 时,依然是满足条件的,即应输出 "Yes"。
简单的并查集题,代码:
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=100005;
int fa[maxn];
bool vis[maxn];
int find(int x)
{
while(x!=fa[x])
x=fa[x];
return x;
}
int main()
{
int n,m,i,a,b;
while(scanf("%d%d",&n,&m)&&n!=-1&&m!=-1)
{
memset(vis,false,sizeof(vis));
bool flag=true;
for(i=1;i<=maxn;i++)
fa[i]=i;
fa[m]=n;
vis[n]=vis[m]=true;
if(n==0&&m==0) {printf("Yes\n");continue;}
while(scanf("%d%d",&n,&m)&&n!=0&&m!=0)
{
vis[n]=vis[m]=true;
a=find(n);
b=find(m);
if(a!=b)
fa[b]=a;
else flag=false;
}
int k=0;
for(i=1;i<maxn;i++)
if(fa[i]==i&&vis[i])
k++;
if(k>1) flag=false;//判断是否联通
if(flag) printf("Yes\n");
else printf("No\n");
}
return 0;
}