SSL2060 迷宮

迷宮

Time Limit:10000MS Memory Limit:65536K
Case Time Limit:1000MS

Description

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

Input

輸入包含多組數據,每組數據是一個以0 0結尾的整數對列表,表示了一條通道連接的兩個房間的編號。房間的編號至少爲1,且不超過100000。每兩組數據之間有一個空行。
整個文件以兩個-1結尾。

Output

對於輸入的每一組數據,輸出僅包括一行。如果該迷宮符合小希的思路,那麼輸出”1”,否則輸出”0”。

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

1
1
0

做法:顯然有並查集直接解。。。

代碼如下:

#include <cstdio>
#include <cstring>
#include <iostream>
#include <string>
#define max(x,y) ((x) > (y) ? (x) : (y))
#define N 100007
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define erg(i, x) for (int i = ls[x]; i; i = e[i].next) 
#define fill(x, y) memset(x, y, sizeof(x))
using namespace std;
int f[N], cnt, dcnt, ddcnt;
bool v[N];

int read()
{
    int s = 0, p = 1;
    char ch = getchar();
    while ((ch < '0' || ch > '9') && ch != '-') ch = getchar();
    if (ch == '-')  p = -1, ch = getchar();
    while (ch >= '0' && ch <= '9')      s = s * 10 + ch - '0', ch = getchar();
    return s * p;
}

int find(int x)
{
    if (f[x] == 0)  return x;
    f[x] = find(f[x]);
    return f[x];
}

int main()
{
    //freopen("migong.in", "r", stdin);
    //freopen("migong.out", "w", stdout);
    int x, y;
    x = read(); y = read();
    while (x != -1 && y != -1)
    {
        bool bb = 0;
        int q, p;
        cnt = 0;
        dcnt = 0;
        ddcnt = 0;
        fill(v, 0);
        fill(f, 0);
        while (x != 0 && y != 0)
        {
            ddcnt++;
            q = find(x), p = find(y);
            if (q != p)
            {
                cnt++;
                f[q] = p;
                if (!v[x])  dcnt++, v[x] = 1;
                if (!v[y])  dcnt++, v[y] = 1;   
            }
            x = read();
            y = read();
        }
        if (cnt != dcnt - 1 || ddcnt != cnt)    bb = 1;
        if (bb) printf("0\n");
        else printf("1\n");
        x = read(); y = read();
    }
    fclose(stdin);
    fclose(stdout);
    return 0;
}
發佈了192 篇原創文章 · 獲贊 10 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章