标签:
1 package ccf_text2014_12; 2 3 import java.util.Scanner; 4 5 public class BestGuanGai2 { 6 7 static final int MAX = Integer.MAX_VALUE; 8 9 static int primAlgorithm(int[][] graphMatrix, int vertexNumber, int initialVertex) { 10 int minCost = 0; 11 boolean[] visited = new boolean[vertexNumber + 1]; 12 for (int i = 0; i < vertexNumber + 1; i++) { 13 visited[i] = false; 14 } 15 16 int position = initialVertex; 17 visited[position] = true; 18 int[] lowCostInLine = new int[vertexNumber + 1]; 19 int min = MAX; 20 21 for (int i = 1; i < vertexNumber + 1; i++) { 22 lowCostInLine[i] = graphMatrix[position][i]; 23 } 24 for (int i = 1; i < vertexNumber; i++) { 25 for (int j = 1; j < vertexNumber + 1; j++) { 26 if (visited[j] == false && lowCostInLine[j] < min) { 27 min = lowCostInLine[j]; 28 position = j; 29 } 30 } 31 minCost += min; 32 min = MAX; 33 visited[position] = true; 34 for (int j = 1; j < vertexNumber + 1; j++) { 35 if (visited[j] == false && graphMatrix[position][j] < lowCostInLine[j]) { 36 lowCostInLine[j] = graphMatrix[position][j]; 37 } 38 } 39 } 40 return minCost; 41 } 42 43 public static void main(String[] args) { 44 Scanner sc = new Scanner(System.in); 45 int n, m; 46 n = sc.nextInt(); 47 m = sc.nextInt(); 48 int[][] adjMatrix = new int[n + 1][n + 1]; 49 int result = 0; 50 51 for (int i = 1; i < n + 1; i++) { 52 for (int j = 1; j < n + 1; j++) { 53 adjMatrix[i][j] = MAX; 54 } 55 } 56 for (int i = 0; i < m; i++) { 57 int begin = sc.nextInt(); 58 int end = sc.nextInt(); 59 int weight = sc.nextInt(); 60 adjMatrix[begin][end] = weight; 61 adjMatrix[end][begin] = weight; 62 } 63 result = primAlgorithm(adjMatrix, n, 4); 64 System.out.println(result); 65 } 66 }
运行结果:
ps:上述代码采用普里姆Prim算法生成用于解决最优路径的最小生成树,该代码在CCF认证平台上的得分与选择加入最小生成树顶点集的初始定点initialVertex以及系统运行环境有关,具体情况见图,有时可以满分100分通过,有时会因为运行超时只能得90分甚至80分,各位可以看看哪里还可以进行优化,将代码复制到CCF认证平台上进行测试时,注意其提交要求,我的程序没有使用package语句来定义包的信息。(如果定义了将无法评测),所以需要将以上代码的package语句删除
标签:
原文地址:http://www.cnblogs.com/haimishasha/p/5357436.html