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("No\n");

47                break;

48            }

49 

50        }

51        if(i>n)

52            printf("Yes\n");

53     }

54     return 0;

55 }
View Code


双向查询,看能否回到原点.....  

你可能感兴趣的:(HDU)