【poj1182】 食物鏈

http://poj.org/problem?id=1182 (題目鏈接)

題意:中文題

Solution
  帶權並查集。
  神犇博客,秒懂
  %3運用的很巧妙。

代碼:

// poj1182
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<cmath>
#define LL long long
#define inf 2147483640
#define Pi 3.1415926535898
#define free(a) freopen(a".in","r",stdin),freopen(a".out","w",stdout);
using namespace std;

int fa[1000010],r[1000010],n,k;

int find(int x) {
    if (x!=fa[x]) {
        int fx=find(fa[x]);
        r[x]=(r[x]+r[fa[x]])%3;
        fa[x]=fx;
    }
    return fa[x];
}
bool Union(int x,int y,int type) {
    int fx,fy;
    fx=find(x);fy=find(y);
    if (fx==fy) {
        if ((r[y]-r[x]+3)%3!=type) return 1;
        else return 0;
    }
    fa[fy]=fx;
    r[fy]=(r[x]-r[y]+type+3)%3;
    return 0;
}
int main() {
    scanf("%d%d",&n,&k);
    for (int i=1;i<=n;i++) fa[i]=i;
    memset(r,0,sizeof(r));
    int sum=0;
    while (k--) {
        int d,x,y;
        scanf("%d%d%d",&d,&x,&y);
        if (x>n || y>n || (x==y && d==2)) sum++;
        else if (Union(x,y,d-1)) sum++;
    }
    printf("%d",sum);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章