https://vjudge.net/problem/POJ-1182
And check the classic questions
For each animal create 3 elements, x, x+N, x+2*N (representing that x belongs to class A, class B and class C, respectively).
Putting two elements in a group means they happen at the same time.
Got stuck with illegal data a few times.
1 #include<iostream> 2 #include<cstdio> 3 #include<queue> 4 #include<cstring> 5 #include<algorithm> 6 #include<cmath> 7 #include<stack> 8 #define lson l, m, rt<<1 9 #define rson m+1, r, rt<<1|1 10 #define IO ios::sync_with_stdio(false);cin.tie(0); 11 #define INF 0x3f3f3f3f 12 typedef unsigned long long ll; 13 using namespace std; 14 const int N = 50000; 15 int n, k, d, x, y, ans=0; 16 int pre[50010*3]; 17 int find(int x) 18 { 19 while(x != pre[x]){ 20 x = pre[x]; 21 } 22 return x; 23 } 24 int is_same(int a, int b) 25 { 26 int tx = find(a); 27 pre[a] = tx; 28 int ty = find(b); 29 pre[b] = ty; 30 if(tx == ty) return 1; 31 else return 0; 32 } 33 void join(int a, int b) 34 { 35 int tx = find(a); 36 int ty = find(b); 37 pre[tx] = ty; 38 } 39 void solve() 40 { 41 if (d == 1 ){ // x and y are equivalent 42 if (x > n||x<= 0 ||y > n||y<= 0 ){ // invalid 43 ans++ ; 44 return ; 45 } 46 else if (is_same(x, y+N)||is_same(x, y+ 2 *N)) // conflict situation, B eats A, C eats A 47 ans++ ; 48 else { 49 join(x, y); 50 join(x+N, y+ N); 51 join(x+2 *N, y+ 2 * N); 52 } 53 } 54 else if (d == 2 ){ // x eats y 55 if (x > n||x<= 0 ||y > n||y< = 0 ){ // Illegal 56 ans++ ; 57 return ; 58 } 59 else if (is_same(x, y)||is_same(x, y+ 2 *N)) // conflict situation, A and B, C eats A 60 ans++ ; 61 else { 62 join(x, y+N); 63 join(x+N, y+2*N); 64 join(x+2*N, y); 65 } 66 } 67 } 68 int main() 69 { 70 for(int i = 0; i <= N*3; i++){ 71 pre[i] = i; 72 } 73 scanf("%d%d", &n, &k); 74 for(int i = 0; i < k; i++){ 75 scanf("%d%d%d", &d, &x, &y); 76 solve(); 77 } 78 printf("%d\n", ans); 79 return 0; 80 }