P3366 【模板】最小生成树
#include<bits/stdc++.h>
using namespace std;
#define int long long
constexpr int maxn=2e4+10;
constexpr int maxm=2e5+10;
int n,m;
int fa[maxn];
typedef struct edge
{
int u,v,w;
edge()=default;
edge(int a,int b,int c):u(a),v(b),w(c){}
bool operator <(const edge& x) const
{
return this->w<x.w;
}
};
edge es[maxm];
void init()
{
for(int i=1;i<=n;++i)
{
fa[i]=i;
}
}
int find_root(int x)
{
return fa[x]==x?x:fa[x]=find_root(fa[x]);
}
void join(int x,int y)
{
int xr=find_root(x);
int yr=find_root(y);
if(xr!=yr)
{
fa[xr]=yr;
}
}
int cnt,ans;
signed main()
{
scanf("%lld%lld",&n,&m);
init();
for(int i=1,x,y,z;i<=m;++i)
{
scanf("%lld%lld%lld",&x,&y,&z);
es[i]={x,y,z};
}
sort(es+1,es+m+1);
for(int i=1;i<=m;++i)
{
edge& e=es[i];
if(find_root(e.u)!=find_root(e.v))
{
join(e.u,e.v);
ans+=e.w;
++cnt;
}
}
if(cnt!=n-1)
{
printf("orz");
}
else
{
printf("%lld",ans);
}
return 0;
}
https://www.luogu.com.cn/problem/P3366