HDU1863(最小生成树)

来源:互联网 发布:js实现隐藏div 编辑:程序博客网 时间:2024/06/05 18:04

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1863

 

package D0803;/*prim算法水过 * 注意一点,就是如果在集合中找不到最小的路径了,肯定图是不联通的直接输出?,否则肯定有结果 *  * */import java.util.*;public class HDU1863 {static int[][] G;static int[] dist;static int s = 1;// 普里姆斯算法求最小生成树public static void prim(int n) {boolean[] p = new boolean[n + 1];int sum = 0;// 保存最短路径for (int i = 1; i <= n; i++) {p[i] = false;if (i != s)dist[i] = G[s][i];}p[s] = true;dist[s] = 0;for (int i = 1; i <= n - 1; i++) {int min = Integer.MAX_VALUE;int k = -1;for (int j = 1; j <= n; j++) {if (!p[j] && dist[j] < min) {min = dist[j];k = j;}}if (k == -1) {//说明不能联通了System.out.println("?");return;}sum += min;p[k] = true;for (int j = 1; j <= n; j++) {if (!p[j] && dist[j] > G[k][j]) {dist[j] = G[k][j];}}}System.out.println(sum);}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n, m;while (sc.hasNext()) {m = sc.nextInt();n = sc.nextInt();if (m == 0)break;G = new int[n + 1][n + 1];// 初始化for (int i = 1; i <= n; i++)for (int j = 1; j <= n; j++)G[i][j] = Integer.MAX_VALUE;dist = new int[n + 1];while (m-- > 0) {int f = sc.nextInt();int t = sc.nextInt();int w = sc.nextInt();if (G[f][t] > w) {G[f][t] = w;G[t][f] = w;}}prim(n);}}}