Boruvka算法模板
Boruvka
时间复杂度: $O(m \log n)$
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PLL;
#define x first
#define y second
const ll N=1e5+1e3,M=1e1+1e2;
ll n,m;
ll x,y,z;
ll t[2*N],weigh[2*N],nex[2*N],h[5*M],cnt;
PLL minm[5*M];
ll fa[5*M];
ll ans;
ll find(ll x)
{
if(x!=fa[x])fa[x]=find(fa[x]);
return fa[x];
}
void add(ll u,ll v,ll w)
{
++cnt;
t[cnt]=v;
weigh[cnt]=w;
nex[cnt]=h[u];
h[u]=cnt;
}
void boruvka()
{
for(ll i=1;i<=n;i++)fa[i]=i;
ll res=n,last=n;
while(true)
{
memset(minm,127,sizeof minm);
for(ll i=1;i<=n;i++)
{
for(ll j=h[i];j;j=nex[j])
{
ll a=find(i),b=find(t[j]);
if(a==b)continue;
if(minm[a].x>weigh[j])
{
minm[a].x=weigh[j];
minm[a].y=t[j];
}
}
}
for(ll i=1;i<=n;i++)
{
if(i!=find(i)||minm[i].x==minm[0].x)continue;
res--;
fa[find(minm[i].y)]=i;
ans+=minm[i].x;
}
if(res==last)
{
puts("impossible");
exit(0);
}
if(res==1)break;
last=res;
}
cout<<ans;
}
signed main()
{
ios::sync_with_stdio(false);
cin>>n>>m;
for(ll i=1;i<=m;i++)
{
cin>>x>>y>>z;
add(x,y,z);
add(y,x,z);
}
boruvka();
}