【带偏移量的并查集】:poj***,Butterfly


输入
输入包含多组数据,以文件结束符为终止。

每组数据第一行为两个整数,分别是n和m:
n为蝴蝶的数量,编号从0到n-1
m为关系的数量

接下来是m组关系数据,每组数据占一行,为三个整数,前两个整数表示蝴蝶的编号,第三个整数为关系的种类(相同或者不同):
0为相同,1为不同

1 < n <= 1000
1 < m <= 100000
输出
合理就输出YES
不合理就输出NO
样例输入
3 3
0 1 0
1 2 1
0 2 1
3 3
0 1 0
1 2 1
0 2 0
样例输出
YES
NO

注意关系如何更新:

# include<iostream>
using namespace std;

# define N 1005

struct NODE
{
    int p,r;//0表示与父亲同类,1表示不同
};

NODE node[N];

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

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

int main()
{
    int n,m,i,j,k,a,b,ap,bp;
    bool bug;

    while(cin>>n>>m)
    {
        MakeSet(n);
        bug=false;

        for(i=1;i<=m;i++)
        {
            cin>>a>>b>>k;
            ap=FindParent(a);
            bp=FindParent(b);
            if(ap==bp)
            {
                if( (k==0&&node[a].r!=node[b].r) || (k==1&&node[a].r==node[b].r) )
                {
                    bug=true;
                }
            }
            else //union
            {
                node[bp].p=ap;
                if(k==0)
                {
                    node[bp].r= node[a].r==node[b].r? 0:1;
                }
                else
                {
                    node[bp].r= node[a].r==node[b].r? 1:0;
                }
            }
        }

        if(bug)
        {
            cout<<"NO"<<endl;
        }
        else
        {
            cout<<"YES"<<endl;
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值