P2024 食物链

题面:https://www.luogu.org/problemnew/show/P2024

本题是带权并查集模板题,要注意的是种类一共有三种,之后套公式判断是否合法,记录不合法即可。

Code:
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=50005;
int f[N],p[N],n,k,ans;
int find(int x){
    if(x!=f[x]){
        int fa=f[x];
        f[x]=find(f[x]);
        p[x]=(p[x]+p[fa])%3;
    }
    return f[x];
}
bool unionn(int d,int x,int y){
    int fx=find(x),fy=find(y);
    if(fx==fy){
        if((p[y]-p[x]+3)%3!=d){
            return 1;
        }
        else{
            return 0;
        }
    }
    f[fy]=fx;
    p[fy]=(p[x]-p[y]+d+3)%3;
    return 0;
}
int main(){
    int d,x,y;
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++){
        f[i]=i;
        p[i]=0;
    }
    for(int i=1;i<=k;i++){
        scanf("%d%d%d",&d,&x,&y);
        if(x>n||y>n||(x==y&&d==2)){
            ans++;
            continue;
        }
        if(unionn(d-1,x,y)){
            ans++;
        }
    }
    printf("%d\n",ans);
    return 0;
}
posted @ 2019-07-16 15:07  prestige  阅读(124)  评论(0编辑  收藏  举报