hdu 5627 并查集

来源:互联网 发布:如何在淘宝店发通告 编辑:程序博客网 时间:2024/06/07 14:22



链接:戳这里


Clarke and MST

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)

Problem Description
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−1 edges. Each two points of n points can reach each other. The size of a spanning tree is generated by bit operation AND with values of n−1 edges. 
Now he wants to figure out the maximum spanning tree.
 
Input
The first line contains an integer 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), denoting the number of points and the number of edge respectively. 
Then m lines followed, each line contains three integers x,y,w(1≤x,y≤n,0≤w≤109), denoting an edge between x,y with value w. 
The number of test case with n,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条边,求最大生成树(这里的最大指的是所有边的权值取&操作最大


思路:

考虑当前是最大生成树必须满足所有权值的and操作要最大,枚举答案所要的(1<<i)

然后对满足取and操作的所有边加入并查集判断是否可以构成生成树


代码:

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<string>#include<vector>#include <ctime>#include<queue>#include<set>#include<map>#include<list>#include<stack>#include<iomanip>#include<cmath>#include<bitset>#define mst(ss,b) memset((ss),(b),sizeof(ss))///#pragma comment(linker, "/STACK:102400000,102400000")typedef long long ll;typedef long double ld;#define INF (1ll<<60)-1#define Max 1e9using namespace std;int n,m;int u[300100],v[300100],w[300100];int fa[300100];int Find(int x){    if(x!=fa[x])        fa[x]=Find(fa[x]);    return fa[x];}int main(){    int T;    scanf("%d",&T);    while(T--){        scanf("%d%d",&n,&m);        for(int i=1;i<=m;i++) scanf("%d%d%d",&u[i],&v[i],&w[i]);        int ans=0;        for(int i=30;i>=0;i--){            ans+=(1<<i);            for(int j=1;j<=n;j++) fa[j]=j;            int cnt=0;            for(int j=1;j<=m;j++){                if((w[j]&ans)==ans){                    int X=Find(u[j]);                    int Y=Find(v[j]);                    if(X!=Y) {                        fa[X]=Y;                        cnt++;                    }                }            }            if(cnt!=n-1) ans-=(1<<i);        }        printf("%d\n",ans);    }    return 0;}


0 0
原创粉丝点击