POJ1182 食物链

http://poj.org/problem?id=1182


并查集。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <map>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

#define N 50005

int n,k,p[N],t[N];

void init()
{
    int i;
    for (i=1;i<=n;i++)
    {
        p[i]=i;
        t[i]=0;
    }
}

int root(int s)
{
    if (p[s]==s) return s;

    int st=p[s];
    p[s]=root(p[s]);

    t[s]=(t[s]+t[st])%3;

    return p[s];
}

void un(int x,int y,int z)
{
    int rx,ry;

    rx=root(x);
    ry=root(y);

    p[ry]=rx;
    t[ry]=(t[x]-z-t[y]+6)%3;
}

int main()
{
    freopen("a","r",stdin);

    int i;
    scanf("%d%d",&n,&k);
    init();
    int sum=0,x,y,z;

    for (i=1;i<=k;i++)
    {
        scanf("%d%d%d",&z,&x,&y);

        if (x>n || y>n) sum++;
        else if (x==y && z==2) sum++;
        else
        {
            int rx,ry;
            rx=root(x);
            ry=root(y);

            if (rx==ry)
            {
                if (z==1 && t[x]!=t[y]) sum++;
                if (z==2 && (t[x]+3-t[y])%3!=1) sum++;
            }
            else un(x,y,z-1);
        }
    }

    cout<<sum<<endl;

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值