题意:就是求最小生成树的边权值和
prim算法求最小生成树
1 import java.util.Scanner; 2 import java.util.Arrays; 3 /* 4 prim 5 */ 6 public class Main{ 7 static int map[][]; //存储邻接矩阵 8 static boolean visit[]; //标记加入的结点 9 static int n; 10 static int INF = 0x3f3f3f3f; 11 12 public static int prim(){ 13 int sum=0; 14 visit = new boolean[n]; 15 visit[0] = true; 16 17 for(int i=0;i<n-1;i++){ //n个结点需要n-1条边,循环n-1次 18 int min = INF; 19 int u = 0; //保存下一个要加入树的结点下标 20 for(int j=1;j<n;j++){ 21 if(visit[j]==false&&map[0][j]<min){ 22 min = map[0][j]; 23 u = j; 24 } 25 } 26 visit[u] = true; //将结点加入,标记置为true 27 sum+=min; 28 for(int j=1;j<n;j++){ //更新数据 29 if(visit[j]==false&&map[u][j]<map[0][j]) 30 map[0][j] = map[u][j]; 31 } 32 } 33 return sum; 34 } 35 36 public static void main(String[] args){ 37 Scanner in = new Scanner(System.in); 38 while(in.hasNext()){ 39 n = in.nextInt(); 40 if(n==0) 41 break; 42 map = new int[n][n]; 43 for(int i=0;i<n;i++) 44 Arrays.fill(map[i],INF); 45 for(int i=0;i<n-1;i++){ 46 char chx = in.next().charAt(0); 47 int j = in.nextInt(); 48 while(j!=0){ 49 j--; 50 char chy = in.next().charAt(0); 51 int y = chy - ‘A‘; 52 int cost = in.nextInt(); 53 map[i][y] = map[y][i] = cost; 54 } 55 } 56 System.out.println(prim()); 57 } 58 } 59 }
Kruskal算法求最小生成树
时间: 2024-12-28 20:45:08