Minimal spanning tree, just learned the prim algorithm.
The weight of each edge is preprocessed, c[i][j] = C[i][j] + p[i] + p[j] where c[i][j] is the input weight, p[i],p[j] is the cost required to connect the two nodes.
#include <stdio.h>#include<string.h>#include<math.h>#include<algorithm>using namespacestd;Const intMAXN =1010;intC[MAXN][MAXN];//adjacency MatrixintX[MAXN], Y[MAXN];//The x array represents the shortest distance from the I node to the collection Y array represents the I node and which point in the collection is the shortest distanceintP[MAXN];intMain () {intSB; scanf ("%d", &SB); while(sb--) { intN, M, I, J, u, V, cost; scanf ("%d", &N); for(i =1; I <= N; i++) scanf ("%d", &P[i]); for(i =1; I <= N; i++) for(j =1; J <= N; J + +) scanf ("%d", &C[i][j]); for(i =1; I <= N; i++) for(j =1; J <= N; J + +) C[i][j] = C[i][j] + p[i] +P[j]; for(i =1; I <= N; i++) X[i] = c[1][i], y[i] =1; y[1] = -1;//Y[i] = = 1 indicates that the I node has been put into the collection inttot =1;//a point has been put into the collection intAns =0; while(1) { intMincost =0x7FFFFFFF, V, flag =0; for(i =1; I <= N; i++)if(Y[i]! =-1&& X[i] < mincost) flag =1, v = i, mincost =X[i]; if(!flag) Break; Y[V]= -1; tot++; Ans = ans +X[v]; for(i =1; I <= N; i++)if(Y[i]! =-1&& C[v][i] < X[i]) x[i] = C[v][i], y[i] =v; } if(tot = n) printf ("%d\n", ans); Elseprintf"No way!\n"); } return 0;}
Zoj 1586 QS Network