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);
}



你可能感兴趣的:(ACM,poj)