poj1182 食物链

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

const int M = 50005;

struct node
{
    int p;
    int relation;

}s[M];

int n, m;

int Find(int x)
{
    if(x == s[x].p)
        return x;
    int t = s[x].p;
    s[x].p = Find(t);
    s[x].relation = (s[x].relation + s[t].relation) % 3; //路径压缩,推理得到。
    return s[x].p;
}

int main()
{
    int a, b, d;
    int x, y;
    int ans;

    scanf("%d%d", &n, &m);

    for(int i = 1; i <= n; i++) {

        s[i].p = i;
        s[i].relation = 0;
    }

    ans = 0;

    for(int i = 1; i <= m; i++) {

        scanf("%d%d%d", &d, &a, &b);

        if(a > n || b > n) {

            ans++;
            continue;
        }
        if(d == 2 && a == b) {

            ans++;
            continue;
        }
        x = Find(a);
        y = Find(b);

        if(x != y)
        {
            s[y].p = x;
            s[y].relation = (3 + d - 1 + s[a].relation - s[b].relation) %3; //由向量的到此公式。
        }
        else
        {
            if(d == 1 && s[a].relation != s[b].relation) {

                ans++;
                continue;
            }
            if(d == 2 &&(3 + s[b].relation - s[a].relation) % 3 != d - 1) { //由向量公式,
                              // a --> 根,== s[b].relation   根--> b == s[a].relation
                ans++;
                continue;
            }
        }
    }
    printf("%d\n", ans);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值