HDU 1272 小希的迷宫 题解

来源:互联网 发布:销售数据分析表格模板 编辑:程序博客网 时间:2024/05/29 17:32

题意

上次Gardon的迷宫城堡小希玩了很久(见Problem B),现在她也想设计一个迷宫让Gardon来走。但是她设计迷宫的思路不一样,首先她认为所有的通道都应该是双向连通的,就是说如果有一个通道连通了房间A和B,那么既可以通过它从房间A走到房间B,也可以通过它从房间B走到房间A,为了提高难度,小希希望任意两个房间有且仅有一条路径可以相通(除非走了回头路)。小希现在把她的设计图给你,让你帮忙判断她的设计图是否符合她的设计思路。

思路

并查集,如果当加入一条边的时候他们已经在同一集合中那么显然不行,如果最后有多个元素数大于1的集合也是不行的,不过空树却是可以的

代码

#include <cstdio>int father[100001];int cnt[100001];int findfather(int x){    if(father[x]==x)        return x;    else return father[x]=findfather(father[x]);}int main(){    int x,y,f,cntt;    while(1)    {        for(int i=1;i<=100000;i++)            father[i]=i;        f=0;        scanf("%d%d",&x,&y);        if(x==-1&&y==-1)            break;        if(x==0&&y==0)        {            printf("Yes\n");            continue;        }        father[y]=x;        while(1)        {            scanf("%d%d",&x,&y);            if(x==0&&y==0)                break;            if(findfather(y)==findfather(x))                f=1;            father[findfather(y)]=findfather(x);        }        for(int i=1;i<=100000;i++)            cnt[findfather(i)]++;        cntt=0;        for(int i=1;i<=100000;i++)            if(cnt[i]>1)                cntt++;        if(f||cntt>1)            printf("No\n");        else printf("Yes\n");        for(int i=1;i<=100000;i++)            cnt[i]=0;    }    return 0;}