#include<stdio.h>
#include<stdlib.h>
#define N 1100
struct node {
int u,v,w;
}bian[110000];
int pre[N];
int cmp(const void *a,const void *b) {
return (*(struct node *)b).w-(*(struct node *)a).w;
}
int find(int x) {
if(x!=pre[x])
pre[x]=find(pre[x]);
return pre[x];
}
int main() {
int n,m,i,j,a,b,k;
while(scanf("%d%d",&n,&m)!=EOF) {
for(i=1;i<=n;i++)
pre[i]=i;
for(i=0;i<m;i++)
scanf("%d%d%d",&bian[i].u,&bian[i].v,&bian[i].w);
qsort(bian,m,sizeof(bian[0]),cmp);
j=0;k=0;
for(i=0;i<m&&j<n-1;i++) {
a=find(bian[i].u);
b=find(bian[i].v);
if(a!=b) {
pre[a]=b;
k+=bian[i].w;
j++;
}
}
if(j==n-1)
printf("%d\n",k);
else
printf("-1\n");
}
return 0;
}
相关文章
- [BZOJ1937][SHOI2004]Mst最小生成树(KM算法,最大费用流)
- POJ 1679 The Unique MST (最小生成树)
- POJ 3625 最小生成树 Prim C++
- POJ 2253 Frogger ( 最短路变形 || 最小生成树 )
- POJ 1861 Network (Kruskal算法+输出的最小生成树里最长的边==最后加入生成树的边权 *【模板】)
- poj 2031Building a Space Station(几何判断+Kruskal最小生成树)
- POJ 1789(最小生成树)
- POJ3241 Object Clustering 曼哈顿最小生成树
- poj 1251 poj 1258 hdu 1863 poj 1287 poj 2421 hdu 1233 最小生成树模板题
- POJ1679The Unique MST(次小生成树)