【HDU - 5627】Clarke and MST(最大生成树,与运算性质,最小生成树MST变形)

题干:

Clarke is a patient with multiple personality disorder. One day he turned into a learner of graph theory. 
He learned some algorithms of minimum spanning tree. Then he had a good idea, he wanted to find the maximum spanning tree with bit operation AND. 
A spanning tree is composed by n−1n−1 edges. Each two points of nn points can reach each other. The size of a spanning tree is generated by bit operation AND with values of n−1n−1 edges. 
Now he wants to figure out the maximum spanning tree.

Input

The first line contains an integer T(1≤T≤5)T(1≤T≤5), the number of test cases. 
For each test case, the first line contains two integers n,m(2≤n≤300000,1≤m≤300000)n,m(2≤n≤300000,1≤m≤300000), denoting the number of points and the number of edge respectively. 
Then mm lines followed, each line contains three integers x,y,w(1≤x,y≤n,0≤w≤109)x,y,w(1≤x,y≤n,0≤w≤109), denoting an edge between x,yx,y with value ww. 
The number of test case with n,m>100000n,m>100000 will not exceed 1. 

Output

For each test case, print a line contained an integer represented the answer. If there is no any spanning tree, print 0.

Sample Input

1
4 5
1 2 5
1 3 3
1 4 2
2 3 1
3 4 7

Sample Output

1

题目大意:

  给一棵n个点m条边的无向图,问你最大与运算生成树多少权值是多少,如果不连通输出0。

解题报告:

  贪心不难发现其实就是求最大生成树。

AC代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define ll long long
#define pb push_back
#define pm make_pair
using namespace std;
const int MAX = 6e5 + 5;
struct Edge {
	int u,v;
	ll w;
} e[MAX];
int n,m;
bool cmp(Edge a,Edge b) {
	return a.w > b.w;
}
int f[MAX];
int getf(int v) {
	return f[v] == v ? v : f[v] = getf(f[v]);
}
void merge(int u,int v) {
	int t1 = getf(u),t2 = getf(v);
	f[t2] = t1;
}
int main()
{
	int t;
	cin>>t;
	while(t--) {
		scanf("%d%d",&n,&m);
		for(int i = 1; i<=n; i++) f[i] = i;
		for(int a,b,i = 1; i<=m; i++) {
			ll w;
			scanf("%d%d%lld",&a,&b,&w);
			e[i].u = a;e[i].v = b;e[i].w = w;
		}
		sort(e+1,e+m+1,cmp);
		ll ans = 1LL<<62;ans--;
		ll no = ans;
//		cout <<ans <<endl;
//		while(ans) {
//			printf("%lld",ans%2);
//			ans>>=1;
//		}
		int cnt = 0;
		for(int i = 1; i<=m; i++) {
			if(getf(e[i].u) != getf(e[i].v)) {
				ans = ans & e[i].w;
				merge(e[i].u,e[i].v);
				cnt++;
			}
		}
		if(cnt != n-1) printf("0\n");
		else printf("%lld\n",ans);
	} 


	return 0 ;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值