POJ1182 食物链 ACM解题报告(并查集+路径压缩难题)

这题真的是做的我都想吐了,WA了几次之后就跪了,然后百度题解,原来是要路径压缩,把所有的并入一个集合,真的是过于巧妙了。

题解链接http://blog.csdn.net/c0de4fun/article/details/7318642/

#include<iostream>
#include<cstdio>
#include<cctype>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<stack>
using namespace std;
#define MAX 50005
typedef long long LL;
const double pi=3.141592653589793;
const int INF=1e9;
const double inf=1e20;
const double eps=1e-6;
struct animal
{
    int num;
    int father;
    int relation;//0和父亲同类,1被父亲吃,2吃父亲
} ani[MAX];
int findfa(int x)
{
    if(ani[x].father==ani[x].num) return ani[x].father;
    int temp=ani[x].father;
    ani[x].father=findfa(ani[x].father);
    ani[x].relation=(ani[x].relation+ani[temp].relation)%3;
    return ani[x].father;
}
void unionn(int x,int y,int a,int b,int d)
{
    ani[b].father=a;
    ani[b].relation=(3-ani[y].relation+(d-1)+ani[x].relation)%3;
}
int main()
{
    int n,k,ans=0;
    scanf("%d%d",&n,&k);
    for(int i=1; i<=n; i++)
    {
        ani[i].num=i;
        ani[i].father=i;
        ani[i].relation=0;
    }
    while(k--)
    {
        int d,x,y;
        scanf("%d%d%d",&d,&x,&y);//x是y的父亲
        if(x>n||y>n)
        {
            ans++;
            continue;
        }
        if(d==1)
        {
            int a=findfa(x);
            int b=findfa(y);
            if(a!=b) unionn(x,y,a,b,d);
            else
            {
                if(ani[x].relation!=ani[y].relation) ans++;
            }
        }
        if(d==2)
        {
            if(x==y)
            {
                ans++;
                continue;
            }
            int a=findfa(x);
            int b=findfa(y);
            if(a!=b) unionn(x,y,a,b,d);
            else
            {
                if(((ani[y].relation+3-ani[x].relation)%3)!=1) ans++;
            }
        }
    }
    printf("%d\n",ans);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值