【带偏移量的并查集】:poj2492,A Bug's Life


带偏移量

注意如何union:关系的更新分四种情况,自己推理一下就好。

else //union
            {
                node[yp].p=xp;
                node[yp].r= node[x].r==node[y].r? 1:0;
            }
如何find:

int xp=node[x].p;
        node[x].p=FindParent(xp);
        node[x].r= node[x].r==node[xp].r? 0:1;
        return node[x].p;


注意,最终结果输出形式,两个换行!!!坑爹,PE了3次!!!





# include<stdio.h>
# include<iostream>
using namespace std;

# define M 2005

struct NODE
{
    int p,r;
};

NODE node[M];


void MakeSet(int m)
{
    for(int i=1;i<=m;i++)
    {
        node[i].p=i;
        node[i].r=0;
    }
}

int FindParent(int x)
{
    if(node[x].p==x)
    {
        return x;
    }
    else
    {
        int xp=node[x].p;
        node[x].p=FindParent(xp);
        node[x].r= node[x].r==node[xp].r? 0:1;
        return node[x].p;
    }
}

int main()
{
    int i,j,k,n,m,t,x,y,xp,yp;
    bool assumption;

    scanf("%d",&n);
    for(i=1;i<=n;i++)
    {
        scanf("%d%d",&m,&t);
        MakeSet(m);
        assumption=true;
        for(j=1;j<=t;j++)
        {
            scanf("%d%d",&x,&y);
            xp=FindParent(x);
            yp=FindParent(y);
            if(xp==yp)
            {
                if(node[x].r==node[y].r)
                {
                    //两者parent相同,两者又能交配,如果假设正确,两者相对parent的relation应该不同
                    //node[x].r==node[y].r,说明假设错误
                    assumption=false;
                }
            }
            else //union
            {
                node[yp].p=xp;
                node[yp].r= node[x].r==node[y].r? 1:0;
            }
        }

        printf("Scenario #%d:\n",i);
        if(assumption==false)
        {
            printf("Suspicious bugs found!\n\n");
        }
        else
        {
            printf("No suspicious bugs found!\n\n");
        }
        /*
        if(assumption==false)
        {
            cout<<"Scenario #"<<i<<":"<<endl<<"Suspicious bugs found!"<<endl;
        }
        else
        {
            cout<<"Scenario #"<<i<<":"<<endl<<"No suspicious bugs found!"<<endl;
        }
        printf("Scenario #%d:\n",i);
        if(!assumption)puts("Suspicious bugs found!\n");
        else puts("No suspicious bugs found!\n");
        */
    }

    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值