http://acm.hdu.edu.cn/showproblem.php?pid=1272
题意要点:任意两个房间有且仅有一条路径可以相通,用并查集
法1)
#include<iostream>
#include<cstdio>
#include<set>
using namespace std;
const int N=100005;
bool flag;
int father[N],rank[N],MAX;
int find(int x)//(1,2)#(2,3)(3,4)#(1,5)--1->2->3->4->5
{
while(x!=father[x])
{
x=father[x];
}
return x;
}
void Union(int x,int y)
{
x=find(x),y=find(y);
if(x!=y)
{
father[x]=y;
rank[y]+=rank[x];
if(MAX<rank[y])
MAX=rank[y];
}
else
flag=1;
}
int main()
{
int x,y,i;
while(scanf("%d%d",&x,&y)&&x!=-1&&y!=-1)//
{
if(x==0&&y==0)
{printf("Yes\n");continue;}
set<int>s1;
s1.insert(x);s1.insert(y);
for(i=0;i<N;i++)
{father[i]=i;rank[i]=1;}
MAX=1;flag=0;
Union(x,y);
while(scanf("%d%d",&x,&y)&&x||y)
{
Union(x,y);
s1.insert(x);s1.insert(y);
}
if(s1.size()!=MAX||flag)//查看是否所有点都可相互到达
printf("No\n");
else
printf("Yes\n");
}
return 0;
}
for(i=0;i<k;i++)
{
if(vis[node[i].x]==0)
{
count++;
vis[node[i].x]=1;
}
if(vis[node[i].y]==0)
{
count++;
vis[node[i].y]=1;
}
x=Find(node[i].x),y=Find(node[i].y);
count--;
if(x!=y) father[y]=x;
else flag=1;
}
if(flag||count!=1) printf("No\n");
else printf("Yes\n");