#include<iostream>
#include<cstdio>
#include<string.h>
#include<string>
#include<stack>
#include<set>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#define ll __int64
#define lll unsigned long long
#define MAX 1000009
#define eps 1e-8
#define INF 0xfffffff
#define mod 1000000007
/*
题意:Prim
想法:模板
*/
using namespace std;
int n,m;
int Edge[1009][1009];//邻接矩阵
int lowcost[1009];//存放顶点集合A内各顶点到顶点集合B内各顶点权值最小边的权值
int nearvex[1009];//记录顶点集合A内各顶点距离顶点集合B内哪个顶点最近,当nearvcex[] = -1,表示当前点属于B
void prim(int u0)
{
int sum = 0;
for(int i = 1; i<=n; i++) //初始化
{
lowcost[i] = Edge[u0][i];
nearvex[i] = u0;
}
nearvex[u0] = -1;
for(int i = 1; i<n; i++)
{
int min = INF;
int v = -1;
for(int j = 1; j<=n; j++)
{
if(nearvex[j]!=-1&&lowcost[j]<min)
{
v = j;
min = lowcost[j];
}
}
if(v!=-1)//v==-1表示没找到权值最小的边
{
//printf("%d %d %d\n",nearvex[v],v,lowcost[v]);
nearvex[v] = -1;
sum+=lowcost[v];
for(int j = 1; j<=n; j++)
{
if(nearvex[j]!=-1&&Edge[v][j]<lowcost[j])
{
lowcost[j] = Edge[v][j];
nearvex[j] = v;
}
}
}
}
//printf("sum = %d\n",sum);
}
int main()
{
int i,j;
int u,v,w;
scanf("%d%d",&n,&m);
memset(Edge,0,sizeof(Edge));
for(i = 1; i<=m; i++)
{
scanf("%d%d%d",&u,&v,&w);
Edge[u][v] = Edge[v][u] = w;
}
for(i = 1; i<=n; i++)
{
for(j = 1; j<=n; j++)
{
if(i==j)Edge[i][j] = 0;
else if(Edge[i][j]==0)
{
Edge[i][j] = INF;
}
}
}
prim(1);
return 0;
}
#include<cstdio>
#include<string.h>
#include<string>
#include<stack>
#include<set>
#include<algorithm>
#include<cmath>
#include<vector>
#include<map>
#define ll __int64
#define lll unsigned long long
#define MAX 1000009
#define eps 1e-8
#define INF 0xfffffff
#define mod 1000000007
/*
题意:Prim
想法:模板
*/
using namespace std;
int n,m;
int Edge[1009][1009];//邻接矩阵
int lowcost[1009];//存放顶点集合A内各顶点到顶点集合B内各顶点权值最小边的权值
int nearvex[1009];//记录顶点集合A内各顶点距离顶点集合B内哪个顶点最近,当nearvcex[] = -1,表示当前点属于B
void prim(int u0)
{
int sum = 0;
for(int i = 1; i<=n; i++) //初始化
{
lowcost[i] = Edge[u0][i];
nearvex[i] = u0;
}
nearvex[u0] = -1;
for(int i = 1; i<n; i++)
{
int min = INF;
int v = -1;
for(int j = 1; j<=n; j++)
{
if(nearvex[j]!=-1&&lowcost[j]<min)
{
v = j;
min = lowcost[j];
}
}
if(v!=-1)//v==-1表示没找到权值最小的边
{
//printf("%d %d %d\n",nearvex[v],v,lowcost[v]);
nearvex[v] = -1;
sum+=lowcost[v];
for(int j = 1; j<=n; j++)
{
if(nearvex[j]!=-1&&Edge[v][j]<lowcost[j])
{
lowcost[j] = Edge[v][j];
nearvex[j] = v;
}
}
}
}
//printf("sum = %d\n",sum);
}
int main()
{
int i,j;
int u,v,w;
scanf("%d%d",&n,&m);
memset(Edge,0,sizeof(Edge));
for(i = 1; i<=m; i++)
{
scanf("%d%d%d",&u,&v,&w);
Edge[u][v] = Edge[v][u] = w;
}
for(i = 1; i<=n; i++)
{
for(j = 1; j<=n; j++)
{
if(i==j)Edge[i][j] = 0;
else if(Edge[i][j]==0)
{
Edge[i][j] = INF;
}
}
}
prim(1);
return 0;
}