Input
輸入包含多組數據,每組數據是一個以0 0結尾的整數對列表,表示了一條通道連接的兩個房間的編號。房間的編號至少爲1,且不超過100000。每兩組數據之間有一個空行。
整個文件以兩個-1結尾。
Output
對於輸入的每一組數據,輸出僅包括一行。如果該迷宮符合小希的思路,那麼輸出"Yes",否則輸出"No"。
Sample Input
6 8 5 3 5 2 6 4
5 6 0 0
8 1 7 3 6 2 8 9 7 5
7 4 7 8 7 6 0 0
3 8 6 8 6 4
5 3 5 6 5 2 0 0
-1 -1
Sample Output
Yes
Yes
No
思路:並查集,一開始只想到瞭如果只要兩個點的父親節點是同樣的,那麼就一定有兩條路到其中一個點。結果一直wa後來同學告訴我所有房間必須是全部連通的,因爲要任意兩個點都有一條路,然後直接加了一個rank數組判斷該樹中元素的個數,如果等於一開始給的樹那麼就是可以的否則就是不可以。
<pre name="code" class="html">#include<iostream>
#include<cstdio>
#include <cstring>
using namespace std;
int rank[100005],fa[100005],max1;
int find(int x)
{
int q = x;
while (fa[q] != q)
{
q = fa[q];
}
int w = x;
while (w != q)
{
int t = fa[w];
fa[w] = q;
w = t;
}
return w;
}
int uni(int x, int y)
{
int x1 = find(x);
int y1 = find(y);
rank[x1] += rank[y1];
if(rank[x1] > max1)
{
max1 = rank[x1];
}
if(x1 == y1)
{
return 0;
}
else
{
fa[y1] = x1;
}
return 1;
}
int main()
{
int a,b,i,ok,count ;
while (scanf("%d %d",&a,&b)&&(a!=-1&&b!=-1))
{
count = 1;
for(i = 0; i < 100005; i++)
{
fa[i] = i;
rank[i] =1;
}
max1 = 0;
ok = 0;
if(a == 0&&b == 0)
{
cout<<"Yes"<<endl;
continue;
}
uni(a,b);
while (1)
{
scanf("%d %d",&a,&b);
count ++;
if(a == 0&& b == 0)
{
break;
count--;
}
int e = uni(a,b);
if(e == 0)
{
ok = 1;
}
}
if(ok == 1 || max1 != count)
{
cout<<"No"<<endl;
}
else
{
cout<<"Yes"<<endl;
}
}
return 0;
}