#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
#define Maxn 23333
#define Maxm 23333
struct edge
{
int u,v,w;
}edges[Maxm];
int p[Maxn];
int n,m;
int Find(int x)
{
int s;
for(s=x;p[s]>0;s=p[s]);
while(s!=x)//路径压缩
{
int tmp=p[x];
p[x]=s;
x=tmp;
}
return s;
}
void Union(int a,int b)
{
int r1=Find(a),r2=Find(b);
int tmp=p[r1]+p[r2];
if(p[r1]>p[r2])
{
p[r1]=r2;
p[r2]=tmp;
}
else
{
p[r2]=r1;
p[r1]=tmp;
}
}
bool cmp(edge a,edge b)
{
if (a.w>b.w) return false;
return true;
}
void Kruskal()
{
int sum=0;
int num=0;
int u,v;
memset(p,-1,sizeof(p));
for(int i=1;i<=m;i++)
{
u=edges[i].u;
v=edges[i].v;
if(Find(u)!=Find(v))
{
sum+=edges[i].w;
Union(u,v);
num++;
}
if(num>=n-1) break;
}
cout<<sum<<endl;
}
int main()
{
cin>>n>>m;
int u,v,w;
for(int i=1;i<=m;i++)
{
cin>>u>>v>>w;
edges[i].u=u;
edges[i].v=v;
edges[i].w=w;
}
sort(edges+1,edges+m+1,cmp);
Kruskal();
return 0;
#include <string.h>
#include <algorithm>
using namespace std;
#define Maxn 23333
#define Maxm 23333
struct edge
{
int u,v,w;
}edges[Maxm];
int p[Maxn];
int n,m;
int Find(int x)
{
int s;
for(s=x;p[s]>0;s=p[s]);
while(s!=x)//路径压缩
{
int tmp=p[x];
p[x]=s;
x=tmp;
}
return s;
}
void Union(int a,int b)
{
int r1=Find(a),r2=Find(b);
int tmp=p[r1]+p[r2];
if(p[r1]>p[r2])
{
p[r1]=r2;
p[r2]=tmp;
}
else
{
p[r2]=r1;
p[r1]=tmp;
}
}
bool cmp(edge a,edge b)
{
if (a.w>b.w) return false;
return true;
}
void Kruskal()
{
int sum=0;
int num=0;
int u,v;
memset(p,-1,sizeof(p));
for(int i=1;i<=m;i++)
{
u=edges[i].u;
v=edges[i].v;
if(Find(u)!=Find(v))
{
sum+=edges[i].w;
Union(u,v);
num++;
}
if(num>=n-1) break;
}
cout<<sum<<endl;
}
int main()
{
cin>>n>>m;
int u,v,w;
for(int i=1;i<=m;i++)
{
cin>>u>>v>>w;
edges[i].u=u;
edges[i].v=v;
edges[i].w=w;
}
sort(edges+1,edges+m+1,cmp);
Kruskal();
return 0;
}
//Kruskal适用于稀疏图 时间复杂度为O(e log(e))