生成树
Description
复习了 10086 遍最小生成树之后,风老板认为最小生成树的东西太简单了,但是他想考验一下队友 ZKL ,于是提出了新的问题。对于一个无向图,给出一个 x ,风老板想让 ZKL 告诉他这个图是否存在一棵生成树,对于树上的每条边权 ai ,满足 (a1&a2&…&an)&x=x (’ & '符号代表按位与运算) , 然而这个问题对于 ZKL 来说太难了,于是 ZKL 向你求助。
Input
第一行三个正整数 n,m,x ,表示有 n 个点,m 条边, x 即上文中给出的数。 (1≤n≤2×1e5,0≤m≤1e6,0≤x≤1e9)
接下来 m 行,每行三个正整数 u,v,w ,表示存在一条连通 u,v 的长度为 w 的无向边。(1≤u,v≤n,0≤w≤1e9)
Output
输出一行一个整数,即满足条件的生成树的边权和,如果存在多颗满足条件的生成树,则输出边权和的最小值。如果不存在满足条件的生成树,则输出" −1 "。
Samples
input
3 4 2
1 2 1
1 3 6
1 3 4
3 2 2
output
8
input
3 2 2
1 2 1
2 3 2
output
-1
Hint
给出的图可能存在自环和重边。
Author
ZHANG, Kaili
题解: 要满足(a1&a2&…&an)&x=x的条件即满足ai&x==x。接下来就是跑最小生成树。
#include<list>
#include<string.h>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<cstring>
#include<vector>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxn = 2e5 + 10;
const int inf = 0x3f3f3f3f;
const int Base =131;
const ll INF = 1ll << 62;
//const double PI = acos(-1);
const double eps = 1e-7;
const int mod = 1e9+7;
#define mem(arry,value) memset(arry,value,sizeof arry)
#define speed {ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); }
const int maxm = 1e6+10;
int n,m,x;
int fa[maxn];
struct Edge{
int u,v,w;
Edge(){}
Edge(int u,int v,int w=inf):u(u),v(v),w(w){}
bool operator<(Edge tmp){//重载小于号使升序排序
return w<tmp.w;
}
}e[maxm];
void init(){
for(int i=0;i<=n;i++)fa[i]=i;
}
int Find(int x){
return x==fa[x]?x:fa[x]=Find(fa[x]);
}
void Union(int x,int y){
int fx=Find(x);
fa[fx]=Find(y);
}
int main(){
ll res=0,cnt=0;
scanf("%d %d %d",&n,&m,&x);
init();
for(int i=0;i<m;i++){
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
e[i]=Edge(a,b,c);
}
sort(e,e+m);
for(int i=0;i<m;i++){
int u=e[i].u,v=e[i].v,w=e[i].w;
if(Find(u)==Find(v)||(w&x)!=x)continue;//用并查集判断有无成环与判断是否满足题意
Union(u,v);
cnt++;
res+=w;
if(cnt==n-1)break;//当加边的数量等于点数量减一时说明可以找到
}
if(cnt==n-1)printf("%lld\n",res);
else printf("-1\n");
system("pause");
return 0;
}