Input
The first line of the input contains a positive integer N, indicating that there are n vertices in the graph. N cannot exceed 50. There are n integers separated by spaces in each row in the next n rows. For the J integer of row I, if it is not 0, it indicates that vertex I and vertex J are directly connected and the cost is the corresponding value. 0 indicates no direct connection. When I and j are equal, make sure that the corresponding integer is 0. The input ensures that the adjacent matrix is a symmetric matrix, that is, the input graph is an undirected graph, and the graph only has one connected component.
Output
There is only one integer, that is, the total cost of the Minimum Spanning Tree. Note the line feed at the end of the line.
Sample Input
4 0 2 4 0 2 0 3 4 3 0 1 0 5 1 0
Sample output
6
1 # include <stdio. h> 2 # define N 55 3 # define INF 600000 4 # define inf2 600001 5 typedef struct G {6 int arc [N] [N]; 7 int arcnum, vernum; 8 int maxweight; 9} graph; 10 typedef struct {11 int adjvex; 12 INT lowcost; 13} closedge; 14 void create (graph * g, int N) {15 int I, j; 16g-> vernum = G-> arcnum = N; 17G-> maxweight = 0; 18 for (I = 0; I <G-> arcnum; I ++) 19 for (j = 0; j <G-> arcnum; j ++) {20 scanf ("% d", & G-> RC [I] [J]); 21 if (G-> maxweight <G-> arc [I] [J]) 22g-> maxweight = G-> arc [I] [J]; 23} 24} 25 void prim (graph * g, Int & spent) {26 closedge [N]; 27 int I, J, K, Min, minver; 28 // initialization array closedge29 for (I = 0; I <G-> vernum; I ++) {30 closedge [I]. adjvex = 0; // 31 from node 0 if (G-> arc [0] [I]) 32 closedge [I]. lowcost = G-> arc [0] [I]; 33 else34 closedge [I]. lowcost = inf; 35} 36 37 closedge [0]. lowcost = inf2; 38 39 for (j = 0; J <G-> vernum-1; j ++) {40 min = G-> maxweight; 41 // select the smallest side 42 for (k = 0; k <G-> vernum; k ++) 43 If (closedge [K]. lowcost & min> closedge [K]. lowcost) {44 min = closedge [K]. lowcost; 45 minver = K; // closedge [K]. adjvex46} 47 spent + = min; 48 closedge [minver]. lowcost = inf2; // Add the selected set 49 // find the vertex minver to the "cost" minver = 1; 50 for (k = 0; k <G-> vernum; k ++) {51 if (closedge [K]. lowcost! = Inf2 & G-> arc [minver] [k] <closedge [K]. lowcost & G-> arc [minver] [k]) {52 closedge [K]. adjvex = K; 53 closedge [K]. lowcost = G-> arc [minver] [k]; 54} 55} 56} 57} 58 int main () {59 int N; 60 graph G; 61 scanf ("% d", & N); 62 create (& G, n); 63 int m = 0; 64 prim (& G, M ); 65 printf ("% d \ n", m); 66 return 0; 67}
Minimum Spanning Tree