HDU ACM 1272 小希的迷宫(并查集)
http://acm.hdu.edu.cn/showproblem.php?pid=1272
题目要求有两个条件:1.在给定图中无环
2.给定的图有且仅有有1个连通分支
判断环:在输入时判断点a点b是否有相同的根节点,有相同根节点再加一条直接连通的边就有环.
判断连通分支数:判断有几个跟节点 if(father[i]==i)
View Code
1 #include <iostream> 2 using namespace std; 3 const int MAX = 100000 + 100; 4 int father[MAX]; 5 int rank1[MAX]; 6 int sign[MAX]; 7 void Make_Set(int x)//初始化 8 { 9 father[x] = x; 10 rank1[x] = 0; 11 } 12 13 int Find_Set(int x)//找根节点 14 { 15 int i=0; 16 while(father[x] != x) 17 { 18 sign[i++] = x; 19 x = father[x]; 20 } 21 for(i;i>=1;i--) 22 { 23 father[sign[i-1]] = x; 24 } 25 return x; 26 } 27 28 29 void Union(int x,int y)//合并 30 { 31 x = Find_Set(x); 32 y = Find_Set(y); 33 if(x == y) 34 { 35 return; 36 } 37 if(rank1[x] > rank1[y]) 38 { 39 father[y] = x; 40 } 41 else if(rank1[x] < rank1[y]) 42 { 43 father[x] = y; 44 } 45 else if(rank1[x] ==rank1[y]) 46 { 47 father[x] = y; 48 rank1[y]++; 49 } 50 } 51 52 int main() 53 { 54 while(1) 55 { 56 int i; 57 int mark = 0; 58 int used[MAX]={0}; 59 for(i=1;i<=MAX-1;i++) 60 { 61 Make_Set(i); 62 } 63 for(i=1;i<=MAX-1;i++) 64 { 65 int a,b; 66 cin>>a>>b; 67 if(a + b == 0) 68 { 69 break; 70 } 71 if(a == -1 && b == -1) 72 { 73 return 0; 74 } 75 used[a] = 1; 76 used[b] = 1; 77 int ra = Find_Set(a); 78 int rb = Find_Set(b); 79 if(ra == rb) 80 { 81 mark = 1; 82 } 83 Union(a,b); 84 } 85 int sum=0; 86 for(i=1;i<=MAX-1;i++) 87 { 88 if(father[i]==i && used[i] == 1) 89 { 90 sum++; 91 } 92 } 93 if(sum > 1 || mark == 1) 94 { 95 cout<<"No"<<endl; 96 } 97 else 98 { 99 cout<<"Yes"<<endl; 100 } 101 102 } 103 return 0; 104 }