package graph.prim;
import java.util.Scanner;
public class Prim {
static final int INF = 0x3f3f3f3f;
static final int N = 100;
// 如果s[i]=true,说明顶点i已加入U
static boolean s[] = new boolean[N];
static int c[][] = new int[N][N];
static int closest[] = new int[N];
static int lowcost[] = new int[N];
static void Prim(int n) {
// 初始时,集合中 U 只有一个元素,即顶点 1
s[1] = true;
for (int i = 1; i <= n; i++) {
if (i != 1) {
lowcost[i] = c[1][i];
closest[i] = 1;
s[i] = false;
} else
lowcost[i] = 0;
}
for (int i = 1; i < n; i++) {
int temp = INF;
int t = 1;
// 在集合中 V-u 中寻找距离集合U最近的顶点t
for (int j = 1; j <= n; j++) {
if (!s[j] && lowcost[j] < temp) {
t = j;
temp = lowcost[j];
}
}
if (t == 1)
break; // 找不到 t,跳出循环
s[t] = true; // 否则,t 加入集合U
for (int j = 1; j <= n; j++) { // 更新 lowcost 和 closest
if (!s[j] && c[t][j] < lowcost[j]) {
lowcost[j] = c[t][j];
closest[j] = t;
}
}
}
}
public static void main(String[] args) {
int n, m, u, v, w;
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
int sumcost = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
c[i][j] = INF;
for (int i = 1; i <= m; i++) {
u = scanner.nextInt();
v = scanner.nextInt();
w = scanner.nextInt();
c[u][v] = c[v][u] = w;
}
Prim(n);
System.out.println("数组lowcost:");
for (int i = 1; i <= n; i++)
System.out.print(lowcost[i] + " ");
System.out.println();
for (int i = 1; i <= n; i++)
sumcost += lowcost[i];
System.out.println("最小的花费:" + sumcost);
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/chengqiuming/article/details/125706151
内容来源于网络,如有侵权,请联系作者删除!