The animal kingdom contains three types of animals A, B, and C. The food chains of these three types constitute an interesting ring. A eats B, B eats C, and C eats.
There are n animals numbered 1-n. Every animal is one of A, B, and C, but we don't know which one it is.
There are two ways to describe the relationship between the food chains of the N animals:
The first statement is "1 x Y", indicating that X and Y are similar.
The second statement is "2 x Y", which indicates that X eats y.
This person speaks K sentences one by one for N animals in the preceding two statements. These K sentences are true or false. When one sentence meets the following three conditions, this sentence is a lie, otherwise it is the truth.
1) The current statement conflicts with some of the preceding actual statements;
2) In the current statement, X or Y is greater than N, which is false;
3) The current statement indicates that X eats X, which is a lie.
Your task outputs the total number of false statements based on the given n (1 <= n <= 50,000) and K statements (0 <= k <= 100,000.
Input
The first line is two integers N and K, separated by a space.
Each row in the following K rows contains three positive integers, D, X, and Y, which are separated by a space. D indicates the type of the statement.
If D = 1, X and Y are of the same type.
If D = 2, X eats y.
Output
Only one integer indicates the number of false statements. Analysis: the idea of this question is exactly the same as that of the question, but he added a kind of operation called x y, Which is similar. In fact, this is well handled, as long as the offset relationship is set to 0 after the merger, the code can be:
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 using namespace std; 5 6 const int maxn = 50005; 7 8 int fa[maxn], num[maxn]; 9 10 void init(int n) {11 for(int i = 0; i <= n; i++) {12 fa[i] = i;13 num[i] = 0;14 }15 }16 17 int find(int i) {18 if(fa[i] == i) {19 return i;20 }21 int fi = fa[i];22 fa[i] = find(fa[i]);23 num[i] = (num[i] + num[fi] + 6) % 3;24 return fa[i];25 }26 27 void unin(int u, int v) {28 int fu = find(u); int fv = find(v);29 if(fu != fv) {30 fa[fv] = fu;31 num[fv] = (num[fv] + (num[u] + 1 - num[v]) + 6) % 3;32 }33 }34 35 void unin2(int u, int v) {36 int fu = find(u); int fv = find(v);37 if(fu != fv) {38 fa[fv] = fu;39 num[fv] = (num[fv] + (num[u] - num[v]) + 6) % 3;40 }41 }42 43 int main() {44 int n, k;45 int c, a, b;46 scanf("%d %d",&n, &k);47 int ans = 0;48 init(n);49 while(k--) {50 scanf("%d %d %d",&c, &a, &b);51 52 if(a > n || b > n) {53 ans++;54 continue;55 } 56 if(c == 2 && a == b) {57 ans++;58 continue;59 }60 if(c == 1) {61 if(find(a) == find(b) ) {62 if(num[a] != num[b]) {63 ans++;64 }65 } else {66 unin2(a, b);67 }68 } else {69 if(find(a) == find(b) ) {70 if(num[b] != ( num[a] + 1 ) % 3 ) {71 ans++;72 }73 } else {74 unin(a, b);75 }76 }77 }78 printf("%d\n", ans);79 return 0;80 }View code
Poj1182 food chain [and check the offset of the set + root node]