There are n cities, some of which can be built between cities, and the cost of building different roads is different. Now, we want to know how much it will cost to build a highway to connect all cities so that we can start in any city and reach any other city.
The input contains multiple groups of data in the following format.
The first line contains two integers, n m, representing the number of cities and the number of roads that can be built. (N <= 100) the remaining m rows have three positive integers, a B c, indicating that a highway can be built between City A and City B at the cost of C. Each output group occupies one row, with only the minimum output cost. Sample Input
3 21 2 11 3 1
Sample output
2
# Include <iostream> using namespace STD; const int intifiy = 65535; typedef struct graph {int Vex [200]; int adj [200] [200]; int numvex, numedge ;} graph; void create (graph * g) {int W, J, I, K; CIN> G-> numvex> G-> numedge; for (I = 1; I <G-> numedge; I ++) for (j = 1; j <G-> numedge; j ++) g-> adj [I] [J] = intifiy; for (I = 1; I <= G-> numvex; I ++) g-> Vex [I] = I; for (k = 0; k <G-> numedge; k ++) {CIN> I> j> W; g-> adj [I] [J] = W; G-> adj [J] [I] = G-> adj [I] [J] ;}} void prim (graph * g) {int min, I, K, J, num = 0; int lowcost [200]; int adj [200]; lowcost [1] = 0; // reserve the right value. adj [1] = 1; // The forward of each node. For (I = 2; I <= G-> numvex; I ++) {lowcost [I] = G-> adj [1] [I]; adj [I] = 0;} for (I = 2; I <= G-> numvex; I ++) {min = intifiy; j = 2; while (j <= G-> numvex) {If (lowcost [J]! = 0 & lowcost [J] <min) {min = lowcost [J]; k = J;} J ++; num + = min ;} lowcost [k] = 0; for (I = 2; I <= G-> numvex; I ++) {If (lowcost [I]! = 0 & lowcost [I]> G-> adj [k] [I]) {lowcost [I] = G-> adj [k] [I]; adj [I] = K ;}}cout <num <Endl ;}int main () {graph * g = new graph; Create (g ); prim (g); System ("pause ");}