import java.util.Arrays;
import java.util.Scanner;
//最小生成树算法模版
public class primMain {
static Scanner in = new Scanner(System.in);
static boolean[] vis = new boolean[1005];
static int[] dis = new int[1005];
static int[][] e = new int[1005][1005];
static int INF = 0x7f7f7f7f;
static int n;//顶点数
static int m;//边数
static void init()
{
for(int i=0;i<m;i++)
Arrays.fill(e[i],INF);
}
static void prim()
{
double cnt = 0.0;
for(int i=0;i<n;i++)
{
dis[i] = e[0][i];//从下标为0的点开始遍历
}
vis[0] = true;
for(int i=0;i<n-1;i++)
{
int min = INF;
int index = -1;
for(int j=0;j<n;j++)
{
if(!vis[j]&&min>dis[j])
{
min = dis[j];
index = j;
}
}
vis[index] = true;
cnt += dis[index];
//更新dis数组
for(int j=0;j<n;j++)
{
if(!vis[j]&&dis[j]>e[index][j])
{
dis[j] = e[index][j];
}
}
}
System.out.println(cnt);
}
static void getMap()
{
for(int i=0;i<m;i++)
{
int a = in.nextInt();
int b = in.nextInt();
int edgelength = in.nextInt();
e[a][b] = e[b][a] = edgelength;
}
}
public static void main(String[] args) {
n = in.nextInt();
m = in.nextInt();
init();
getMap();
prim();
}
}
//测试用例
/*
6 10
0 1 4
0 4 1
0 5 2
1 2 6
1 5 3
2 3 6
2 5 5
3 4 4
3 5 5
4 5 3
*/
01-08
205
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)