小希的迷宮(HDOJ-1272)

Problem Description

上次Gardon的迷宮城堡小希玩了很久(見Problem B),現在她也想設計一個迷宮讓Gardon來走。但是她設計迷宮的思路不一樣,首先她認爲所有的通道都應該是雙向連通的,就是說如果有一個通道連通了房間A和B,那麼既可以通過它從房間A走到房間B,也可以通過它從房間B走到房間A,爲了提高難度,小希希望任意兩個房間有且僅有一條路徑可以相通(除非走了回頭路)。小希現在把她的設計圖給你,讓你幫忙判斷她的設計圖是否符合她的設計思路。比如下面的例子,前兩個是符合條件的,但是最後一個卻有兩種方法從5到達8。

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

Author

Gardon

Source

HDU 2006-4 Programming Contest

思路:

一道簡單的並查集,只需要每次判斷father結點是否相同,相同即爲不行。
比較坑的地方就是要考慮自環和空樹的情況。
看到discuss裏有一個大神直接用|點| = |邊| - 1判斷,非常巧妙,一會兒去思考一下如何證明。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <climits>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <vector>
#include <list>
#define MST(a, b) memset(a, b, sizeof a);
using namespace std;
typedef long long ll;
const int MAXN = 100000 + 100;
int fa[MAXN], u, v;
vector <int> maze;
int find_fa(int x) {
    return fa[x] == x ? fa[x] : fa[x] = find_fa(fa[x]);
}
void merge_fa(int x, int y) {
    int fx = find_fa(x), fy = find_fa(y);
    if (fx != fy) fa[fy] = fx;
}
int main() {
    while (cin >> u >> v) {
        if (u == -1 && v == -1) break;
        bool flag = true;
        if (u && v) {
            maze.clear();
            for (int i = 1; i <= 100000; i++) fa[i] = i;
            maze.push_back(u);
            maze.push_back(v);
            if (find_fa(u) == find_fa(v) && u != v) flag = false;
            else merge_fa(u, v);
            while (cin >> u >> v, u && v) {
                maze.push_back(u);
                maze.push_back(v);
                if (find_fa(u) == find_fa(v) && u != v) flag = false;
                else merge_fa(u, v);
            }
            for (int i = 0; i < maze.size(); i++)
                if (find_fa(maze[i]) != find_fa(maze[0])) {
                    flag = false;
                    break;
                }
        }
        if (flag) cout << "Yes" << endl;
        else cout << "No" << endl;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章