并查集入门题
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1272
#include <iostream>
using namespace std;
#define MAX 100001
// father[x]表示x的父节点
int father[MAX];
// rank[x]表示x的秩
int rank[MAX];
// 初始化
void Make_Set(int n)
{
for(int i=1; i<=n; ++i)
{
father[i] = i;
rank[i] = 0;
}
}
// 查找
int Find_Set(int x)
{
if(x != father[x])
return Find_Set(father[x]);
return x;
}
// 合并
void Union(int x, int y)
{
x = Find_Set(x);
y = Find_Set(y);
if(x == y) // x,y在同一个集合
return;
if(rank[x] > rank[y])
father[y] = x;
else if(rank[x] < rank[y])
father[x] = y;
else
{
rank[y]++;
father[x] = y;
}
}
int main()
{
//freopen("input.txt", "r", stdin);
int a, b;
while(scanf("%d %d", &a, &b))
{
if(a==-1 && b==-1)
break;
if(a==0 && b==0)
{
printf("Yes\n");
continue;
}
Make_Set(MAX);
rank[a]=1;
rank[b]=1;
Union(a, b);
int flag=1; // 表示是否有多条路
while(scanf("%d %d", &a, &b) && (a+b))
{
rank[a]++;
rank[b]++;
if(Find_Set(a) == Find_Set(b)) // 判断两点是否有多条路
flag = 0;
Union(a, b);
}
int cnt = 0;
for(int i=1; i<=MAX; ++i)
if(rank[i] && Find_Set(i) == i)
cnt++;
if(flag && cnt==1)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}