【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 7Sample 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 ; }?
總結
以上是生活随笔為你收集整理的【HDU - 5627】Clarke and MST(最大生成树,与运算性质,最小生成树MST变形)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浦发信用卡白金卡额度多少 三种途径轻松查
- 下一篇: 2021年要避免哪些理财的坑?有哪些常见