并查集 HDU1272

 1 #include <iostream>
 2 #include <map>
 3 #include <cstring>
 4 #include <cstdio>
 5 
 6 using namespace std;
 7 
 8 int father[100010];
 9 int num[100010];
10 
11 int main()
12 {
13     int a,b;
14     while(true)
15     {
16         int flag=1;
17         int time=1;
18         for(int i=1;i<=100000;i++)
19             father[i]=i;
20         for(int i=1;i<=100000;i++)
21             num[i]=1;
22         while(cin>>a>>b)
23         {
24             if(a==0&&b==0)
25                 break;
26             if(a==-1&&b==-1)
27                 goto F1;
28             time++;
29             int fa=a;
30             int fb=b;
31             while(fa!=father[fa])
32             {
33                 fa=father[fa];
34             }
35             while(fb!=father[fb])
36             {
37                 fb=father[fb];
38             }
39             int t1=a;
40             while(t1!=fa)
41             {
42                 int tmp=father[t1];
43                 father[t1]=fa;
44                 t1=tmp;
45             }
46             int t2=b;
47             while(t2!=fb)
48             {
49                 int tmp=father[t2];
50                 father[t2]=fb;
51                 t2=tmp;
52             }
53             if(fa==fb)
54                 flag=0;
55             else
56             {
57                 father[fb]=fa;
58                 num[fa]+=num[fb];
59                 num[fb]=0;
60             }
61         }
62         if(flag)
63         {
64             flag=0;
65             for(int i=1;i<=100000;i++)
66             {
67                 if(num[i]==time)
68                 {
69                     flag=1;
70                 }
71             }
72         }
73         if(flag)
74             cout<<"Yes"<<endl;
75         else
76             cout<<"No"<<endl;
77     }
78     F1:
79     return 0;
80 }
View Code

 

posted @ 2015-08-10 18:27  相儒以沫  阅读(112)  评论(0编辑  收藏  举报