小希的迷宮 HDU - 1272 並查集
阿新 • • 發佈:2021-02-17
技術標籤:並查集
上次Gardon的迷宮城堡小希玩了很久(見Problem B),現在她也想設計一個迷宮讓Gardon來走。但是她設計迷宮的思路不一樣,首先她認為所有的通道都應該是雙向連通的,就是說如果有一個通道連通了房間A和B,那麼既可以通過它從房間A走到房間B,也可以通過它從房間B走到房間A,為了提高難度,小希希望任意兩個房間有且僅有一條路徑可以相通(除非走了回頭路)。小希現在把她的設計圖給你,讓你幫忙判斷她的設計圖是否符合她的設計思路。比如下面的例子,前兩個是符合條件的,但是最後一個卻有兩種方法從5到達8。
input
輸入包含多組資料,每組資料是一個以0 0結尾的整數對列表,表示了一條通道連線的兩個房間的編號。房間的編號至少為1,且不超過100000。每兩組資料之間有一個空行。
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
output
對於輸入的每一組資料,輸出僅包括一行。如果該迷宮符合小希的思路,那麼輸出"Yes",否則輸出"No"。
Yes
Yes
No
code
//Siberian Squirrel
//#include<bits/stdc++.h>
#include<unordered_map>
#include<algorithm>
#include <iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<cmath>
#include<set>
#define ACM_LOCAL
using namespace std;
typedef long long ll;
const double PI = acos(-1);
const double eps = 1e-7;
const int inf = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int N = 1e5 + 10;
const int UP = 1e2 + 10;
int pre[N];
bool f = true;
set<int> st;
void Init(int n){
for(int i = 0; i <= n; ++ i){
pre[i] = i;
}
}
int Find(int x) {
// while(pre[x] != x) x = pre[x];
// return pre[x];
return x == pre[x]? x: pre[x] = Find(pre[x]);
}
void merge(int x, int y){
int fx = Find(x);
int fy = Find(y);
if(fx != fy){
pre[fy] = fx;
} else f = false;
}
inline bool solve(int n, int m, ll res = 0) {
st.clear();
Init(N);
merge(n, m);
st.insert(n);
st.insert(m);
res ++;
while(scanf("%d%d", &n, &m) && n + m) {
merge(n, m);
st.insert(n);
st.insert(m);
res ++;
}
return f && st.size() == res + 1? true: false;
}
int main() {
#ifdef ACM_LOCAL
freopen("input", "r", stdin);
freopen("output", "w", stdout);
#endif
int o = 1, n, m;
// scanf("%d", &o);
while(o --) {
while(scanf("%d%d", &n, &m) && n != -1 && m != -1) {
if(n + m == 0) puts("Yes");
else
printf("%s\n", solve(n, m)? "Yes": "No");
}
}
return 0;
}