hdu 1272 小希的迷宫 解题报告

时间:2021-01-21 16:22:18

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1272

第二条并查集,和畅通工程的解法类似。判断小希的迷宫不符合条件,即有回路。我的做法是,在合并两个集合的时候,当fx = fy,即有共同祖先的时候,说明就有回路。

这题有三点要注意:1、格式问题。题目说的“每两组数据之间有一个空行。”是会PE的!!实际上输出Yes或No之后加多个\n即可,不需要再画蛇添足再输多一个换行。  2、 当整数对列表只有0 0 时,要输出Yes   3、当不相交的集合个数>=2时,也是不符合条件的,要输出No

 #include <iostream>
#include <algorithm>
#include <string.h>
using namespace std; const int maxn = + ;
int set[maxn], flag[maxn];
int sign; int find_set(int x)
{
while (x != set[x])
x = set[x];
return x;
} void union_set(int x, int y)
{
int fx = find_set(x);
// printf("fx = %d\n", fx);
int fy = find_set(y);
// printf("fy = %d\n", fy);
if (fx != fy)
{
set[fx] = fy;
// printf("set[%d] = %d\n", fx, set[fx]);
}
else
sign = ;
} int main()
{
int a, b, i, j, cnt;
memset(set, , sizeof(set));
memset(flag, , sizeof(flag));
i = sign = ;
while (scanf("%d%d", &a, &b) && (a != - || b != -))
{
if (i == && a == && b == ) // i = 0代表列表中的数据是第一组
{
printf("Yes\n");
}
else if (a != && b != )
{
i++;
if (!flag[a] && set[a] != a) // flag的作用是输入数据时当存在多个相同的数据时,保证只需要存入一次set[a],起到类似监视哨的作用
{
set[a] = a;
flag[a] = ;
// printf("set[%d] = %d\n", a, set[a]);
}
if (!flag[b] && set[b] != b)
{
set[b] = b;
flag[b] = ;
// printf("set[%d] = %d\n", b, set[b]);
}
if (a > b)
swap(a, b); // 保证小的数指向的祖先比它大,其实这个判断不要也行
61 union_set(a, b); // 合并a、b元素,使a、b成为一个集合
}
else
{
for (cnt = , j = ; j < maxn; j++)
if (set[j] == j) // 统计不相交集合个数
cnt++;
if (cnt > ) // 不相交集合个数超过1个
sign = ;
if (sign)
printf("No\n");
else
printf("Yes\n");
memset(set, , sizeof(set));
memset(flag, , sizeof(flag));
i = sign = ;
}
}
return ;
}