hdu1182食物链

这道题是并查集的稍微难一点的应用因为有三个元素,详细代码及讲解如下

#include <iostream>
#include <stdio.h>
using namespace std;
int pre[150005];
int find(int x)
{
    int r=x;
    while(r!=pre[r])
    {
        r=pre[r];
    }
    int i=x,j;
    while(pre[i]!=r)
    {
        j=pre[i];
        pre[i]=r;
        i=j;
    }
    return r;
}
void join(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
        pre[fy]=fx;
}
bool same(int x,int y)
{
    return find(x)==find(y);
}
int main()
{
    int n,k,x,y,d;
    scanf("%d%d",&n,&k);
    {
        //本题我定义的是B吃A为x,C吃B为x+n,A吃C为x+2n
        int sum=0;
        for(int i=1; i<=3*n; i++)//因为是三个物种所以分别用xx+n,x+2n表示
            pre[i]=i;
        for(int i=1; i<=k; i++)
        {
            scanf("%d%d%d",&d,&x,&y);
            if(x<=0||y<=0||x>n||y>n)//当标号不在范围内,是假
            {
                sum++;
                continue;
            }
            if(d==1)
            {
                if(same(x,y+n)||same(x+n,y+2*n)||same(x+2*n,y)||same(x,y+2*n)||same(x+n,y)||same(x+2*n,y+n))
                {//这里是只要两物种不相同,那么就是假话
                    sum++;
                    continue;
                }
                join(x,y);//把三种情况都加一遍
                join(x+n,y+n);
                join(x+2*n,y+2*n);
            }
            else if(d==2)
            {
                if(x==y||same(x,y+2*n)||same(x,y)||same(x+n,y)||same(x+n,y+n)||same(x+2*n,y+n)||same(x+2*n,y+2*n))
                {//只要两物种不是按照正常的吃的关系,就是假话
                    sum++;
                    continue;
                }
                join(x,y+n);
                join(x+n,y+2*n);
                join(x+2*n,y);
            }

        }
       printf("%d\n",sum);
    }
return 0;
}

你可能感兴趣的:(并查集)