Bitwise Exclusive-OR Sequence

  •  题意
  1. 给定一个n,m    n表示需要构造n个数   m表示这n个数的m组关系
  2. 随后m行,给出m组a     b    c表示a^b=c 
  3. 如果发生关系中发生矛盾输出-1,否则输出满足条件的n个数的最小和
  • 思路
  1. 我们很容易想到,所有的关系之间会构成多个连通块,每个连通块是独立的,我们需要对每个连通块单独讨论
  2. 如果当前连通块中的某一个数确认了,那么连通块中其他的数必然也将被确认
  3. 我们按位讨论(一共30位),如果当前某个数的第i位确认了(0/1),那么这个连通块中所有的数的的第i位都能确定,那我们直接枚举第0-30位每一位是0还是1,即可以确定所有连通块中的每个数的每一位的0/1情况  对于每一位,取min(cnt[0],cnt[1])就好

代码:

#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define x first
#define y second
#define int long long 
#define debug cout << endl << "------------------------" << endl
typedef long long LL;
typedef pair<int,int>PII;
typedef pair<PII,int>PIII;
const int N=4e5+5;
const int M=1e6+5;
const int mod=998244353;
int n,m,k,q;
int h[N],e[N],ne[N],w[N],idx;
int st[N][35];
int cnt[2];
void add(int a,int b,int c){
	e[idx]=b;
	ne[idx]=h[a];
	w[idx]=c;
	h[a]=idx++;
}
void dfs(int u,int b,int val){
	st[u][b]=val;
	cnt[val]++;
	st[u][b]=val;
	for(int i=h[u];~i;i=ne[i]){
		int j=e[i];
		if(st[j][b]==-1){
			dfs(j,b,((w[i]>>b)&1)^val);
		}else {
			if((((w[i]>>b)&1)^val)!=st[j][b]){
				cout<<"-1";
				exit(0);
			}
		}
	}
}
void solve() {
	memset(h,-1,sizeof h);
	memset(st,-1,sizeof st);
	cin>>n>>m;
	while(m--){
		int a,b,c;
		cin>>a>>b>>c;
		add(a,b,c);
		add(b,a,c);
	}
	int ans=0;
	for(int i=1;i<=n;i++){
		for(int j=0;j<=30;j++){
			if(st[i][j]==-1){
				cnt[1]=0;
				cnt[0]=0;
				dfs(i,j,0);
				ans+=(1<<j)*min(cnt[1],cnt[0]);
			}
		}
	}
	cout<<ans<<endl;
}
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	
	int t=1;
	//cin >> t ;
	
	while(t--) {
		solve();
	}

	return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值