并查集 poj1308

 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <vector>
 5 
 6 using namespace std;
 7 
 8 vector<int> used;
 9 int father[101000];
10 
11 int main()
12 {
13     int time=1;
14     while(true)
15     {
16         for(int i=0;i<=101000;i++)
17         {
18             father[i]=i;
19         }
20         int flag=1;
21         int x,y;
22         used.clear();
23         while(scanf("%d%d",&x,&y)!=EOF)
24         {
25             if(x==-1&&y==-1)
26                 goto F;
27             if(!(x==0&&y==0))
28             {
29                 if(father[y]==y)
30                 {
31                     int fx=x;
32                     while(fx!=father[fx])
33                     {
34                         fx=father[fx];
35                     }
36                     if(fx==y)
37                         flag=0;
38                     father[y]=fx;
39                     used.push_back(x);
40                     used.push_back(y);
41                     while(x!=fx)
42                     {
43                         int tmp=father[x];
44                         father[x]=fx;
45                         x=tmp;
46                     }
47                 }
48                 else
49                     flag=0;
50             }
51             else
52             {
53                 if(used.empty())
54                     printf("Case %d is a tree.\n",time);
55                 else
56                 {
57                     int f=used[0];
58                     int ff;
59                     while(f!=father[f])
60                         f=father[f];
61                     for(int i=1;i<used.size();i++)
62                     {
63                         ff=used[i];
64                         while(ff!=father[ff])
65                         {
66                             ff=father[ff];
67                         }
68                         if(ff!=f)
69                         {
70                             flag=0;
71                             break;
72                         }
73                     }
74                     if(flag)
75                         printf("Case %d is a tree.\n",time);
76                     else
77                         printf("Case %d is not a tree.\n",time);
78                 }
79                 time++;
80                 break;
81             }
82         }
83     }
84 F:
85     return 0;
86 }
View Code

 

posted @ 2015-08-17 09:50  相儒以沫  阅读(122)  评论(0编辑  收藏  举报