题目:http://acm.hdu.edu.cn/showproblem.php?pid=1272
一道并查集的基础题目。
注意两点
#include<iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
const int maxn = 100005;
int father[maxn];
int rank[maxn];
void make_set(int x){
father[x] =x;
rank[x] =0;
}
int find_set(int x){
if(father[x]!= x)
father[x] = find_set(father[x]);
returnfather[x];
}
int union_set(int x,int y){
x =find_set(x);
y =find_set(y);
if(x ==y)
return 0;
if(rank[x]>rank[y]){
father[y] = x;
}
else{
if(rank[x] == rank[y])
rank[y]++;
father[x] = y;
}
return1;
}
int un[maxn];
int main(){
inta,b;
for(int i =1;i < maxn;i++)
make_set(i);
memset(un,0,sizeof(un));
while(scanf("%d%d",&a,&b)&&a!=-1&&b!=-1){
if(a == 0 && b ==0){//千万不要忘了这种边界,WA了好几次
printf("Yes\n");
continue;
}
int ans = 1;
ans &= union_set(a,b);
un[a] = un[b] = 1;
while(scanf("%d%d",&a,&b)&&a+b){
ans &= union_set(a,b);
un[a] = un [b] = 1;
}
int flag = 0;
for(int i = 1;i < maxn;i++)
if(un[i] && father[i] == i)
flag++;
if(flag>1) ans = 0;
if(ans)
printf("Yes\n");
else
printf("No\n");
for(int i = 1;i < maxn;i++)
make_set(i);
memset(un,0,sizeof(un));
}
return0;
}