hdu 1829 A Bug's Life 并查集系列
1 #include "cstdio" 2 #include "iostream" 3 #include "cstring" 4 #include "vector" 5 #include "queue" 6 using namespace std; 7 8 #define MAXN 2222 9 int fa[MAXN]; 10 int rnk[MAXN]; //秩 表示某点与根的距离 11 int n, m; 12 int a, b; 13 bool ok; 14 int k,T; 15 16 inline void init() 17 { 18 ok = false; 19 for (int i = 0; i <= n; ++i) 20 fa[i] = i, rnk[i] = 0; 21 } 22 23 int find(int x) 24 { 25 if (fa[x] == x) return x; 26 int t = find(fa[x]); 27 rnk[x] = (rnk[fa[x]] + rnk[x]) & 1; //得到x的秩 28 fa[x] = t; 29 return fa[x]; 30 } 31 32 void merge(int a, int b) 33 { 34 int x = find(a); 35 int y = find(b); 36 if (x == y) { //根节点相同 37 if (rnk[a] == rnk[b]) //看秩是否相同 38 ok = true; 39 return; 40 } 41 fa[x] = y; 42 rnk[x] = (rnk[a] + rnk[b] + 1) & 1;//根节点不同,得到该点的秩 43 } 44 45 void process() 46 { 47 48 scanf("%d%d",&n,&m); 49 init(); 50 for (int i = 0; i < m; ++i) { 51 scanf("%d%d",&a,&b); 52 merge(a,b); 53 } 54 55 printf("Scenario #%d:\n",++k); 56 if (ok) printf("Suspicious bugs found!\n"); 57 else printf("No suspicious bugs found!\n"); 58 puts(""); 59 } 60 61 int main() 62 { 63 cin >> T; 64 for (int i = 0; i < T; ++ i) 65 process(); 66 //system("pause"); 67 return 0; 68 }