POJ ~ 1182 ~ 食物链 (带权并查集)

参考博客:POJ-1182 食物链

思路:经典的带权并查集。除了并查集那个数组外,多开一个权值数组,或者把两个合成一个结构体数组。权值为每个点与根节点的关系//0:同类 1:吃 2:被吃。

图一:路径压缩 

图二:合并操作

图三:a和b相对关系



//#include<bits/stdc++.h>
#include<cstdio>
#include<iostream>
using namespace std;
const int MAXN = 50005;
int n, m, ans, f[MAXN], w[MAXN];//并查集数组和关系数组
//0:同类 1:吃 2:被吃
void init()
{
    ans = 0;
    for (int i = 0; i <= n; i++)
    {
        f[i] = i; w[i] = 0;
    }
}
int Find(int x)
{
    if (f[x] == x) return x;
    int t = f[x];
    f[x] = Find(f[x]);
    w[x] = (w[x] + w[t]) % 3;
    return f[x];
}
void Union(int a, int b, int D)
{
    int root1 = Find(a), root2 = Find(b);
    if (root1 != root2)
    {
        f[root1] = root2;
        w[root1] = (w[b] + (D - 1) - w[a] + 3) % 3;
    }
    else
    {
        if ((w[a] - w[b] + 3) % 3 != D - 1) ans++;
    }
}
int main()
{
    //while(~scanf("%d%d", &n, &m))不知道为什么用多组输入输出会wa
    scanf("%d%d", &n, &m);
    {
        init();//初始化
        while (m--)
        {
            int D, x, y;
            scanf("%d%d%d", &D, &x, &y);
            if (x > n || y > n || (D == 2 && x == y)) { ans++; continue; }//大于N或者自己吃自己
            Union(x, y, D);
        }
        printf("%d\n", ans);
    }
    return 0;
}
/*
100 7
1 101 1
2 1 2
2 2 3
2 3 3
1 1 3
2 3 1
1 5 5
*/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值