1. 程式人生 > >hdu 1272 小希的迷宮 (並查集)

hdu 1272 小希的迷宮 (並查集)

out 之間 const time oid n) input 方法 desc

小希的迷宮
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 63919 Accepted Submission(s): 20060
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

C/C++:

 1 #include <map>
 2 #include <queue>
 3 #include <cmath>
 4 #include <vector>
 5 #include <string>
 6 #include <cstdio>
 7 #include <cstring>
 8 #include <climits>
 9 #include <iostream>
10 #include <algorithm>
11 #define INF 0xffffff
12 using
namespace std; 13 14 const int my_max = 100005; 15 int a, b, my_pre[my_max + 2], my_book[my_max + 2]; 16 bool my_flag; 17 18 int my_find(int x) 19 { 20 int n = x; 21 while (n != my_pre[n]) 22 n = my_pre[n]; 23 int i = x, j; 24 while (my_pre[i] != n) 25 { 26 j = my_pre[i];
27 my_pre[i] = n; 28 i = j; 29 } 30 return n; 31 } 32 33 void my_join(int aa, int bb) 34 { 35 int n1 = my_find(aa), n2 = my_find(bb); 36 if (n1 != n2) my_pre[n1] = n2; 37 else my_flag = false; 38 } 39 40 int main() 41 { 42 while (scanf("%d%d", &a, &b), a != -1 || b != -1) 43 { 44 if (a == 0 && b == 0) 45 { 46 printf("Yes\n"); 47 continue; 48 } 49 for (int i = 1; i <= my_max; ++ i) 50 { 51 my_pre[i] = i; 52 my_book[i] = 0; 53 } 54 my_book[a] = my_book[b] = 1; 55 my_join(a, b); 56 57 my_flag = true; 58 while (scanf("%d%d", &a, &b), a || b) 59 { 60 my_join(a, b); 61 my_book[a] = my_book[b] = 1; 62 } 63 64 int my_cnt = 0; 65 for (int i = 1; i <= my_max; ++ i) 66 { 67 if (my_book[i] && my_pre[i] == i) 68 { 69 my_cnt ++; 70 if (my_cnt >= 2) 71 { 72 my_flag = false; 73 break; 74 } 75 } 76 } 77 78 if (my_flag) 79 printf("Yes\n"); 80 else 81 printf("No\n"); 82 } 83 return 0; 84 }

hdu 1272 小希的迷宮 (並查集)