https://vjudge.net/problem/POJ-1182
并查集经典题
对于每只动物创建3个元素,x, x+N, x+2*N(分别表示x属于A类,B类和C类)。
把两个元素放在一个组代表他们同时发生。
被不合法数据卡了几次。
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和y等价 42 if(x > n||x<=0||y > n||y<=0){//不合法 43 ans++; 44 return ; 45 } 46 else if(is_same(x, y+N)||is_same(x, y+2*N))//冲突情况,B吃A,C吃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吃y 55 if(x > n||x<=0||y > n||y<=0){//不合法 56 ans++; 57 return ; 58 } 59 else if(is_same(x, y)||is_same(x, y+2*N)) //冲突情况,A同B,C吃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 }
原文地址:https://www.cnblogs.com/Surprisezang/p/8993215.html
时间: 2024-10-10 17:38:11