G. MinOr Tree

题目链接

G. MinOr Tree

求最小或生成树

解题思路

贪心,并查集

按位考虑,从高位开始,用并查集合并当前边该位为 \(0\)的点,再判断所有点是否组成一棵生成树,如果可以说明该位可以为 \(0\),再删除那些该位为 \(1\) 的边,否则该位必须为 \(1\),删除该位为 \(0\) 的边

  • 时间复杂度:\(O(t\times (n+m)\times logn)\)

代码

// Problem: G. MinOr Tree
// Contest: Codeforces - Codeforces Round #764 (Div. 3)
// URL: https://codeforces.com/contest/1624/problem/G
// Memory Limit: 256 MB
// Time Limit: 2000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=2e5+5;
struct T
{
	int x,y,w;
}tr[N];
int n,t,m,fa[N],v[N];
int get(int x)
{
	return fa[x]==x?x:fa[x]=get(fa[x]);
}
int main()
{
    for(cin>>t;t;t--)
    {
    	memset(v,0,sizeof v);
    	scanf("%d%d",&n,&m);
    	for(int i=1;i<=n;i++)fa[i]=i;
    	for(int i=1;i<=m;i++)scanf("%d%d%d",&tr[i].x,&tr[i].y,&tr[i].w);
    	int res=0;
    	for(int i=30;~i;i--)
    	{
    		for(int j=1;j<=n;j++)fa[j]=j;
    		for(int j=1;j<=m;j++)
    		{
    			if(v[j]||(tr[j].w>>i&1))continue;
    			fa[get(tr[j].x)]=get(tr[j].y);
    		}
    		int f=0;
    		for(int j=1;j<=n;j++)f+=(j==fa[j]);
    		if(f==1)
    		{
    			for(int j=1;j<=m;j++)
    				if(tr[j].w>>i&1)v[j]=true;
    		}
    		else
    		{
    			for(int j=1;j<=m;j++)
    				if(tr[j].w>>i&1==0)v[j]=true;
    			res|=1<<i;
    		}
    			
    	}
    	printf("%d\n",res);
    }
    return 0;
}
posted @ 2022-03-04 17:18  zyy2001  阅读(38)  评论(0编辑  收藏  举报