POJ1182--食物链

题目大意:中文题...

 

分析:对每个动物创建2个元素,i-x,i-y,i-z都用并查集维护。i-x表示i属于x类。


代码:

#include <cstdio>
#include <cstring>
using namespace std;

const int maxn = 55555;
int n, k;
int fa[3*maxn+10];
int ans;

int Find(int x) {
    return fa[x] == x ? x : fa[x] = Find(fa[x]);
}

void Union(int x, int y) {
    int p1 = Find(x);
    int p2 = Find(y);
    if(p1 != p2) fa[p1] = p2;
}

int main () {
    scanf("%d%d", &n, &k);
    memset(fa, -1, sizeof(fa));
    for(int i = 0; i < n; i++) {
        fa[i] = i;
        fa[n+i] = n+i;
        fa[2*n+i] = 2*n+i;
    }
    ans = 0;
    for(int i = 0; i < k; i++) {
        int e, s, t;
        scanf("%d%d%d", &e, &s, &t);
        int x = s-1, y = t-1;
        if(x < 0 || x >= n || y < 0 || y >= n) {
            ans++;
            continue;
        }
        if(e == 1) {
            if(Find(x) == Find(y+n) || Find(x) == Find(y+2*n))
                ans++;
            else {
                Union(x, y);
                Union(x+n, y+n);
                Union(x+2*n, y+2*n);
            }
        }
        else {
            if(Find(x) == Find(y) || Find(x) == Find(y+2*n))
                ans++;
            else {
                Union(x, y+n);
                Union(x+n, y+2*n);
                Union(x+2*n, y);
            }
        }
    }
    printf("%d\n", ans);
    return 0;
}


你可能感兴趣的:(POJ1182--食物链)