HDOJ5627 Clarke and MST (并查集)

原题的链接
this question want us to find a maximum AND operation spanning tree. I use union set to check the connectivity of each edge ,and find answer bit by bit and check each method of how edges join together. my code are as below

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
const int MAX_SIZE=300005;
int pa[MAX_SIZE];
int judge[MAX_SIZE];
int ca,n,m;
struct node
{
    int x,y;
    int w;
}point[MAX_SIZE];
int findset(int v)
{
    if(v==pa[v]) return v;
    else
    {
        return pa[v]=findset(pa[v]);
    }
}
void Union(int a, int b)
{
    int a1 = findset(a);
    int b1 = findset(b);
    if(a1 != b1)        
    {
        pa[a1] = b1;       
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin>>ca;
    while(ca--)
    {
        cin>>n>>m;
        for(int i=1;i<=m;i++)
        {
            cin>>point[i].x>>point[i].y>>point[i].w;
        }
        int ans=0;

        for(int i=30;i>=0;i--)
        {
            for(int j=1;j<=n;j++)
            {
                pa[j]=j;
            }
            for(int j=1;j<=m;j++)
            {
                if(( (point[j].w & ans) == ans) && ( point[j].w >> i & 1) )    //check this whether this method are aviliable
                {
                    judge[j] =1;
                }
                else judge[j] = 0;
            }
            for(int j=1;j<=m;j++)
            {
                if(judge[j])
                {
                    Union(point[j].x,point[j].y);
                }
            }
            int f=1;
            int p=findset(1);
            for(int j=2;j<=n;j++)
            {
                if(findset(j)!=p)
                {
                    f=0;
                }
            }
            if(f) ans|=(1<<i);
        }
        cout<<ans<<endl;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值