- 题意
- 给定一个n,m n表示需要构造n个数 m表示这n个数的m组关系
- 随后m行,给出m组a b c表示a^b=c
- 如果发生关系中发生矛盾输出-1,否则输出满足条件的n个数的最小和
- 思路
- 我们很容易想到,所有的关系之间会构成多个连通块,每个连通块是独立的,我们需要对每个连通块单独讨论
- 如果当前连通块中的某一个数确认了,那么连通块中其他的数必然也将被确认
- 我们按位讨论(一共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;
}