题目描述:
给定一个 n 个点 m 条边的无向图,图中可能存在重边和自环,边权可能为负数。
求最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible。
给定一张边带权的无向图 G=(V,E),其中 V 表示图中点的集合,E 表示图中边的集合,n=|V|,m=|E|。
由 V 中的全部 n 个顶点和 E 中 n−1 条边构成的无向连通子图被称为 G 的一棵生成树,其中边的权值之和最小的生成树被称为无向图 G 的最小生成树。
输入格式
第一行包含两个整数 n 和 m。
接下来 m 行,每行包含三个整数 u,v,w,表示点 u 和点 v 之间存在一条权值为 w 的边。
输出格式
共一行,若存在最小生成树,则输出一个整数,表示最小生成树的树边权重之和,如果最小生成树不存在则输出 impossible。
数据范围
1≤n≤500,
1≤m≤105,
图中涉及边的边权的绝对值均不超过 10000。
输入样例:
4 5
1 2 1
1 3 2
1 4 3
2 3 2
3 4 4
输出样例:
6
总的来说,prim算法和dijkstra算法是比较相似的,主要的区别在于prim算法更新距离是为选中的节点距离所有选中节点中的最短距离,而不是到达节点的最短距离
代码实现:
import java.io.*;
import java.util.*;
public class Main{
public static int[][] g = new int[510][510];
public static int[] d = new int[510];
public static boolean[] st = new boolean[510];
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] lens = br.readLine().split(" ");
int n = Integer.parseInt(lens[0]);
int m = Integer.parseInt(lens[1]);
for (int i = 0; i <= n; i++) Arrays.fill(g[i], 0x3f3f3f3f);
while (m-- > 0){
String[] res = br.readLine().split(" ");
int a = Integer.parseInt(res[0]);
int b = Integer.parseInt(res[1]);
int c = Integer.parseInt(res[2]);
g[a][b] = Math.min(g[a][b], c);
g[b][a] = g[a][b];
}
int t = prim(n);
if (t == -1) System.out.println("impossible");
else System.out.println(t);
}
public static int prim(int n){
Arrays.fill(d, 0x3f3f3f3f);
int res = 0;
for (int i = 0; i < n; i++){
int t = -1;
for (int j = 1; j <= n; j++){
if (!st[j] && (t == -1 || d[t] > d[j]))
t = j;
}
st[t] = true;
if (i > 0 && d[t] == 0x3f3f3f3f) return -1;
if (i > 0) res += d[t];
for (int j = 1; j <= n; j++) d[j] = Math.min(d[j], g[t][j]);//这里更新的是距离已选中的节点中的最短距离
}
return res;
}
}