Use of the prime algorithm
Package Primeapplication;import java.util.scanner;/** * Farmers want to establish an Internet, so that all farmers in the village connect to the Internet, and the total cost is minimal. * Multiple sets of data, each set of data given an n, * then give an n * N size of the adjacency matrix representation of an image, the value represents the edge. * Requires the output of the minimum spanning tree weights and. * */public class Main {public static int maxcost = integer.max_value;//integer maximum value public static void Main (string[] args) {Scann ER input = new Scanner (system.in), int cost, while (Input.hasnext ()) {int n = input.nextint (); int [][]adjmat = new Int[n+1][n +1];for (int i=1;i<=n;i++) {for (int j=1;j<=n;j++) {Adjmat[i][j] = maxcost;}} for (int i=1;i<=n;i++) {for (int j=1;j<=n;j++) {Adjmat[i][j] = Input.nextint ();}} Cost = prime (Adjmat,n); System.out.println (cost);}} The private static int prime (int[][] graph, int n) {/* Lowcost[i] records the minimum weight of the edge at the end of I, and when lowcost[i]=0 represents the end I joins the spanning tree */int lowcost[]=n EW int[n+1]; /* Mst[i] records The starting point of the corresponding lowcost[i], when mst[i]=0 indicates the starting point I joins the spanning tree */int mst[]=new int[n+1]; int min, minid, sum = 0; /* By default Select node 1th joins the spanning tree, starting from node 2nd to initialize */for (int i = 2; I <= n; i++) {/* Shortest distance initialized to the distance from other nodes to number 1th */lowcost[i] = graph[1][i];/* mark Remember that all nodes start with the default number 1thNode */mst[i] = 1; }/* Tag 1th node join spanning tree */mst[1] = 0; /* N nodes require at least n-1 to form a minimum spanning tree */for (int i = 2; I <= n; i++) {min = Maxcost;minid = 0; /* Find the node that satisfies the minimum weight edge of the condition MiniD */for (int j = 2; J <= N; j + +) {/* Edge weight value is small and not in the spanning tree */if (Lowcost[j] < min && L OWCOST[J]! = 0) {min = lowcost[j]; MiniD = j; }/* Output spanning tree edge information: Start, end, weight *///system.out.printf ("%c-%c:%d\n", Mst[minid] + ' A '-1, MiniD + ' a '-1, MIN); /* Cumulative weights */sum + = min; /* Tag node MiniD join spanning Tree */lowcost[minid] = 0; /* Update current node MiniD to other node weights */for (int j = 2; J <= N; j + +) {/* Find smaller weights */if (Graph[minid][j] < lowcost[j ]) {/* Update weight information */lowcost[j] = Graph[minid][j]; /* Update the beginning of the minimum weight edge */mst[j] = MiniD; }}}/* Returns the minimum weight and */return sum;}}
Use of the prime algorithm