Typical primAlgorithm
Such questions can be slightly distorted, such as poj2421
# Include <iostream> # include <map> # define maxn 102 typedef long elem_t; using namespace STD; elem_t prim (int n, elem_t mat [maxn] [maxn]) {elem_t closeedge [maxn], sum = 0, min; int I, j, k; for (I = 0; I <n; I ++) closeedge [I] = mat [0] [I]; // initialize the secondary array for (I = 1; I <n; I ++) {J = 0; while (! Closeedge [J]) J ++; // find the first unclassified point min = closeedge [J]; k = J; // start searching for the next node for (J ++; j <n; j ++) if (closeedge [J] & min> closeedge [J]) {min = closeedge [J]; k = J;} sum + = closeedge [k]; closeedge [k] = 0; For (j = 0; j <N; j ++) // Add a new vertex to the set and reselect the smallest edge if (MAT [k] [J] & mat [k] [J] <closeedge [J]) closeedge [J] = mat [k] [J];} return sum;} int main () {int N, I, j; long result; long distance [maxn] [maxn]; while (CIN> N) {for (I = 0; I <n; I ++) for (j = 0; j <n; j ++) {CIN> distance [I] [J];} result = prim (n, distance); cout <result <Endl ;} return 0 ;}