import java.util.Scanner; public class Main { /** * 4 * 0 2 4 0 * 2 0 3 5 * 4 3 0 1 * 0 5 1 0 * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); int n = in.nextInt(); int[][] weight = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { weight[i][j] = in.nextInt(); } } Prim prim = new Prim(n); MinTree minTree = new MinTree(); minTree.create(n, prim, weight); minTree.prim(prim, 0); } private static class MinTree{ public int[] visited; public int len; public void create(int vertx, Prim prim, int[][] weight) { this.len = vertx; this.visited = new int[len]; prim.weight = weight; } public void prim(Prim prim, int v) { this.visited = new int[len]; visited[v] = 1; int min; int t = -1; int res = 0; for (int i = 1; i < len; i++) { min = Integer.MAX_VALUE; for (int j = 0; j < len; j++) { for (int k = 0; k < len; k++) { if (prim.weight[j][k] != 0 && visited[j] == 1 && visited[k] == 0 && prim.weight[j][k] < min) { t = k; min = prim.weight[j][k]; } } } if (t != -1) { visited[t] = 1; res += min; } } System.out.println(res); } } private static class Prim{ int[][] weight; int vertx; public Prim(int vertx) { this.vertx = vertx; this.weight = new int[vertx][vertx]; } } } /************************************************************** Problem: 2162 User: admin Language: Java Result: Accepted Time:777 ms Memory:41668 kb ****************************************************************/