Boruvka求最小生成树
程序员文章站
2022-03-11 21:17:55
因为牛客多校我第一次见到这个算法:算法大致过程就是因为牛客多校我第一次见到这个算法:算法大致过程就是因为牛客多校我第一次见到这个算法:算法大致过程就是对于每个连通块,每次找出一条最小的出边然后把两个连通块合并每次可以是连通块个数减半然后就得到了一个O((n+m)log n)的做法代码模板:#include #include #include #include #inc....
对于每个连通块,每次找出一条最小的出边
然后把两个连通块合并
每次可以是连通块个数减半
然后就得到了一个O((n+m)log n)的做法
代码模板:
#include <iostream>
#include <cstdio>
#include <stack>
#include <sstream>
#include <limits.h>
#include <vector>
#include <map>
#include <cstring>
#include <deque>
#include <cmath>
#include <iomanip>
#include <queue>
#include <algorithm>
#include <set>
// #define mid ((l + r) >> 1)
#define Lson rt << 1, l , mid
#define Rson rt << 1|1, mid + 1, r
#define ms(a,al) memset(a,al,sizeof(a))
#define log2(a) log(a)/log(2)
#define _for(i,a,b) for( int i = (a); i < (b); ++i)
#define _rep(i,a,b) for( int i = (a); i <= (b); ++i)
#define for_(i,a,b) for( int i = (a); i >= (b); -- i)
#define rep_(i,a,b) for( int i = (a); i > (b); -- i)
#define lowbit(x) ((-x) & x)
#define IOS std::ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define INF 0x3f3f3f3f
#define hash Hash
#define next Next
#define count Count
#define pb push_back
#define f first
#define s second
using namespace std;
const int N = 4e5+10, mod = 1e9 + 9;
const long double eps = 1e-5;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
typedef pair<double,double> PDD;
template<typename T> void read(T &x)
{
x = 0;char ch = getchar();ll f = 1;
while(!isdigit(ch)){if(ch == '-')f*=-1;ch=getchar();}
while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
template<typename T, typename... Args> void read(T &first, Args& ... args)
{
read(first);
read(args...);
}
struct node {
int to, next, w;
}e[N], mi[N];
int fa[N];
int head[N], cnt;
int n,m;
inline int find(int x)
{
return fa[x] == x ? x : fa[x] = find(fa[x]);
}
inline void add(int from, int to, int w)
{
e[cnt] = {to,head[from],w};
head[from] = cnt ++;
}
inline int Borucka()
{
int ans = 0, edg = 0;
while(1)
{
ms(mi,INF);
for(int i = 1; i <= n; ++ i)
for(int j = head[i]; ~j; j = e[j].next)
{
int v = e[j].to, w = e[j].w;
if(find(v) != find(i) && w < mi[find(i)].w)
{
mi[find(i)].w = w, mi[find(i)].to = v;
}
}
int F = 0;
for(int i = 1; i <= n; ++ i)
{
int v = mi[i].to, w = mi[i].w;
if(mi[i].to != mi[0].to && find(i) != find(v))
fa[find(v)] = find(i), ans += w, edg ++, F = 1;
}
if(!F) break;
}
if(edg == n - 1) return ans;
else return -1;
}
int main()
{
read(n,m);
ms(head,-1);
for(int i = 0; i <= n + 1; ++ i) fa[i] = i;
for(int i = 0; i < m; ++ i)
{
int l, r, w;
read(l,r,w);
add(l,r,w);
add(r,l,w);
}
int ans = Borucka();
if(ans == -1) cout << "orz";
else cout << ans << endl;
}
本文地址:https://blog.csdn.net/weixin_45630722/article/details/107590090
推荐阅读