1. 程式人生 > 其它 >HDUOJ ---1269迷宮城堡

HDUOJ ---1269迷宮城堡

http://acm.hdu.edu.cn/showproblem.php?pid=1269

迷宮城堡

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 5596    Accepted Submission(s): 2482

Problem Description

為了訓練小希的方向感,Gardon建立了一座大城堡,裡面有N個房間(N<=10000)和M條通道(M<=100000),每個通道都是單向的,就是說若稱某通道連通了A房間和B房間,只說明可以通過這個通道由A房間到達B房間,但並不說明通過它可以由B房間到達A房間。Gardon需要請你寫個程式確認一下是否任意兩個房間都是相互連通的,即:對於任意的i和j,至少存在一條路徑可以從房間i到房間j,也存在一條路徑可以從房間j到房間i。

Input

輸入包含多組資料,輸入的第一行有兩個數:N和M,接下來的M行每行有兩個數a和b,表示了一條通道可以從A房間來到B房間。檔案最後以兩個0結束。

Output

對於輸入的每組資料,如果任意兩個房間都是相互連線的,輸出"Yes",否則輸出"No"。

Sample Input

3 3

1 2

2 3

3 1

3 3

1 2

2 3

3 2

0 0

Sample Output

Yes

No

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 #define maxn 10000
 5 int shun[maxn+2],fan[maxn+2];
 6 void inti(int n)
 7 {
 8     for(int i=1;i<=n;i++)
 9     {
10         shun[i]=i;
11         fan[i]=i;
12     }
13 }
14 int setfind(int x,int *father)
15 {
16     if(x!=father[x]&&father[x]!=1)  /*以1為root*/
17     {
18      father[x]=setfind(father[x],father);
19     }
20     return father[x];
21 }
22 void colect(int x,int y)
23 {
24     /*等於1不處理,是因為以1為root,設1的祖先為自己*/
25     /*順反尋找節點*/
26     if(x>1)shun[x]=setfind(y,shun);  //去尋找父節點
27     if(y>1)fan[y]=setfind(x,fan);    //去尋找父節點
28 }
29 
30 int main()
31 {
32     int m,n,i,a,b;
33     freopen("test.in","r",stdin);
34     while(~scanf("%d%d",&n,&m)/*,m+n*/)
35     {
36        inti(n);
37        for(i=0;i<m;i++)
38        {
39            scanf("%d%d",&a,&b);
40            colect(a,b);
41        }
42        for(i=1;i<=n;i++)
43        {
44            if(setfind(i,shun)!=1||setfind(i,fan)!=1)
45            {
46                printf("Non");
47                break;
48            }
49 
50        }
51        if(i>n)
52            printf("Yesn");
53     }
54     return 0;
55 }

雙向查詢,看能否回到原點.....