把性别相同的虫子放在同一个集合,然后每读入一对虫子号,判断它们在不在同一集合,在则同性别,不在则继续
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 using namespace std; 5 6 const int maxn = 2005; 7 int fa[maxn]; 8 int Rank[maxn]; 9 int group[maxn]; 10 11 void init(int x){ 12 fa[x] = x; 13 Rank[x] = 0; 14 group[x] = 0; 15 } 16 17 int Find(int x){ 18 if (x == fa[x]) 19 return x; 20 else 21 return fa[x] = Find(fa[x]); 22 } 23 24 void set_union(int x, int y){ 25 int fx = Find(x); 26 int fy = Find(y); 27 if (Rank[fx] > Rank[fy]){ 28 fa[fy] = fx; 29 } 30 else{ 31 fa[fx] = fy; 32 if (Rank[fx] == Rank[fy]) 33 Rank[fy]++; 34 } 35 } 36 37 int main(){ 38 int t; 39 int cnt = 0; 40 scanf("%d", &t); 41 while (t--){ 42 cnt++; 43 int n, m; 44 scanf("%d %d", &n, &m); 45 for (int i = 0; i <= n; i++){ 46 init(i); 47 } 48 bool ans = true; 49 while (m--){ 50 int x; 51 int y; 52 scanf("%d %d", &x, &y); 53 if (ans == false) 54 continue; 55 if (Find(x) == Find(y)){ 56 ans = false; 57 continue; 58 } 59 if (group[x] == 0) 60 group[x] = y; 61 else set_union(group[x], y); 62 if (group[y] == 0) 63 group[y] = x; 64 else 65 set_union(group[y], x); 66 67 } 68 printf("Scenario #%d: ", cnt); 69 if (!ans){ 70 printf("Suspicious bugs found! "); 71 } 72 else 73 printf("No suspicious bugs found! "); 74 if (m != 0){ 75 printf(" "); 76 } 77 } 78 //system("pause"); 79 return 0; 80 }