Question: The number is 1 ~ N bugs, starting to assume that these insects are heterosexual. Then we know that Xi and Yi are mating. Based on the known situation, we can determine whether there is a homosexuality.
This question is very similar to the poj 1182 food chain, but it is easier to update the relationship with the parent node.
The sex array stores the gender relationship with the parent node. If it is the same as the parent node, It is 0; otherwise, it is 1.
Sex [a] = (sex [a] + sex [temp]) % 2 should be updated at the same time of each path compression;
In addition, if X and Y are not in the same set, when merging the two shards, consider the relationship between x px y Py and
parent[px] = py;sex[px] = 1 - (sex[x] ^ sex[y]);
This can be easily simulated on paper.
Two low-level mistakes were made when coding, because once we found that there was a homosexuality, we could output the results, but we had to "Ignore" the remaining unread data"
Because I may be break, this cycle is not completed, and I is not auto-incrementing, in the "Ignore" loop, I must first increase the number
1 //#define LOCAL 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 7 const int maxn = 2000 + 10; 8 int parent[maxn], sex[maxn]; 9 10 int GetParent(int a)11 {12 if(parent[a] == a) return a;13 int temp = parent[a];14 parent[a] = GetParent(parent[a]);15 sex[a] = (sex[a] + sex[temp]) % 2;16 return parent[a];17 }18 19 int main(void)20 {21 #ifdef LOCAL22 freopen("2492in.txt", "r", stdin);23 #endif24 25 int T, kase;26 scanf("%d", &T);27 for(kase = 1; kase <= T; ++kase)28 {29 int n, m, i;30 int x, y;31 bool flag = false;32 scanf("%d%d", &n, &m);33 for(int i = 0; i <= n; ++i)34 {35 parent[i] = i;36 sex[i] = 0;37 }38 for(i = 0; i < m; ++i)39 {40 scanf("%d%d", &x, &y);41 int px = GetParent(x);42 int py = GetParent(y);43 if(px == py)44 {45 if(sex[x] == sex[y])46 {47 flag = true;48 break;49 }50 }51 else52 {53 parent[px] = py;54 sex[px] = 1 - (sex[x] ^ sex[y]);55 }56 }57 for(++i; i < m; ++i)58 scanf("%d%d", &x, &y);59 printf("Scenario #%d:\n%suspicious bugs found!\n\n", kase, flag ? "S" : "No s");60 //if(kase < T) printf("\n");61 }62 return 0;63 }
Code Jun
Poj 2492 (simple and query set) A Bug's Life