P2024

[NOI2001食物链]

题目大意:看那句话当处理

做法:种类并查集,分种类去存每个物种的本身,猎物,天敌

1:开三倍并查集,一倍存本身,二倍存猎物,三倍的天敌

2:合并的时候分别合并三个并查集中的元素,若\((x,y)\)是同类,则\(merge(x,y),merge(x+n,y+n),merge(x+n+n,y+n+n)\)

3:题目限制,若\(x\)\(y\)的天敌,\(y\)\(z\)的天敌,那么根据题目\(z\)就是\(x\)的天敌,具体怎么合并看代码(

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 5e4+5;
int n,k,f[maxn*3],ans;

int find(int x)
{
    return f[x] == x ? x : f[x] = find(f[x]);
}

void merge(int x,int y)
{
    f[find(x)] = find(y);
    return ;
}

int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n*3;i++) f[i] = i;
    for(int i=1;i<=k;i++)
    {
        int op,x,y;
        scanf("%d%d%d",&op,&x,&y);
        if(x > n || y > n)
        {
            ans ++;
            continue;
        }
        if(op == 1)
        {
            if(find(x) == find(y+n) || find(x) == find(y+2*n))
                ans ++;
            else
            {
                merge(x,y);
                merge(x+n,y+n);
                merge(x+2*n,y+2*n);
            }
        }
        if(op == 2)
        {
            if(find(x) == find(y) || find(x) == find(y+n))
                ans ++;
            else
            {
                merge(x,y+2*n);
                merge(x+n,y);
                merge(x+2*n,y+n);
            }
        }
    }
    printf("%d",ans);
    return 0;
}
12-30 02:14