带权并查集模板(poj1182食物链验证)

暑假才做过。。。忘完了,重新复习带权并查集


#include<stdio.h>
using namespace std;

int a,b,error=0;
int n,k,set[50500];
int rank[50500];
int d,x,y;

long findset(int x){
    int y=x;
    if(set[x]==x) return x;
    else y=findset(set[x]);
    rank[x]=(rank[set[x]]+rank[x])%3;
    set[x]=y;
    return y;
}

void unions(int x,int y,int w){
    //long a,b;
    a=findset(x);
    b=findset(y);
    set[b]=a;
    rank[b]=(rank[x]-rank[y]+w+3)%3;

}

int main(){
    scanf("%d %d",&n,&k);
    for(int i=0;i<n;i++){
        set[i]=i;
        rank[i]=0;
    }
    //cout<<n<<k;
    for(int i=0;i<k;i++){
        scanf("%d %d %d",&d,&x,&y);
        //cin>>d>>x>>y;
        if(x>n||y>n) {error++; continue;}
        a=findset(x);
        b=findset(y);
        if(a==b){
            if(d==1&&rank[x]!=rank[y]){error++; continue;}
            if(d==2&&(rank[x]+1)%3!=rank[y]){error++; continue;}
        }
        unions(x,y,d-1);
    }
    cout<<error;
    return 1;
}


你可能感兴趣的:(ini)