食物链

 

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

这题标准带权并查集

#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
int f[50001],d[50001],n,k,d1,x,y,ans;
int find(int x){
    if(x!=f[x]){
        int xx=f[x];
        f[x]=find(f[x]);
        d[x]=(d[x]+d[xx])%3;
    }
    return f[x];
}
int main(){
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++){
        f[i]=i;d[i]=0;
        }
    for(int i=1;i<=k;i++){
        scanf("%d%d%d",&d1,&x,&y);
        if(((d1==2)&&(x==y))||((x>n)||(y>n))){
            ans++;
            continue;
        }
        if(d1==1){
            if(find(x)==find(y)){
                if(d[x]!=d[y]){
                    ans++;
                }
            }
            else{
                d[f[x]]=(d[y]-d[x]+3)%3;
                f[f[x]]=f[y];
            }
        }
        if(d1==2){
            if(find(x)==find(y)){
                if(d[x]!=(d[y]+1)%3){
                    ans++;
                }
            }
            else{
                d[f[x]]=(d[y]-d[x]+4)%3;
                f[f[x]]=f[y];
            }
        }
    }
    printf("%d",ans);
}

 

posted @ 2019-07-05 10:42  [jackeylove]  阅读(437)  评论(0编辑  收藏  举报