食物链 POJ 1182

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

搞了一天这个题了,懵懂状态中,大概理解了,也能自己敲一遍代码。But,只能在这分享几个大牛写的了。。(毕竟自己水平有限,有待提高啊 %>_<%)

http://blog.csdn.net/c0de4fun/article/details/7318642/  

http://www.cnblogs.com/zhengguiping--9876/p/4677668.html

http://www.cnblogs.com/liuxin13/p/4668205.html

      

     

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
#define maxn 52000
int father[maxn], r[maxn];
int Find(int x)
{
    if(x!=father[x])
    {
        int k = father[x];
        father[x] = Find(father[x]);
        r[x] = (r[x]+r[k])%3;
    }
    return father[x];
}

int main()
{
    int n, m, op, x, y, ans=0;

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

    for(int i=0; i<=n; i++)
        father[i] = i;

    memset(r, 0, sizeof(r));

    while(m --)
    {
        scanf("%d %d %d", &op, &x, &y);

        if(x>n || y>n ||(x==y && op==2))
        {
            ans ++;
            continue;
        }

         int rx = Find(x);
         int ry = Find(y);
         op --;

         if((op+r[y])%3 != r[x] && rx==ry)
             ans ++;
         else if(rx!=ry)
         {
             father[rx]=ry;
             r[rx] =(op-r[x]+r[y]+3)%3;///+3是为了防止有负数出现
         }
    }

    printf("%d
", ans);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/daydayupacm/p/5719065.html