Topic Links:
https://vjudge.net/problem/ZOJ-1586
Main topic:
First give a T, representing the T test sample, and then give an n, indicating that there are n QS device, the next line is the cost of the N QS device. Next is the N*n matrix, which represents the cost of links between each of the two QS devices. The minimum cost for all unicom.
Ideas:
Here need to ask for the least cost, because the point and the edge of the right value, simply directly put the two ends of the weights on the edge of the weight value, it becomes a bare MST topic
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <algorithm>5#include <cmath>6#include <queue>7#include <stack>8#include <map>9#include <sstream>Ten using namespacestd; OnetypedefLong Longll; A Const intMAXN = 2e3 +Ten; - Const intINF =1<< -; - intdir[4][2] = {1,0,0,1,-1,0,0,-1}; the intT, N, m, X; - intMAP[MAXN][MAXN];//Save Diagram - intLOWCOST[MAXN], MST[MAXN]; - intA[MAXN]; + voidPrimintU//minimum spanning tree start - { + intSum_mst =0;//minimum Spanning tree weight value A for(inti =1; I <= N; i++)//Initialize two arrays at { -Lowcost[i] =Map[u][i]; -Mst[i] =u; - } -Mst[u] =-1;//set to 1 to indicate that the MST has been added - for(inti =1; I <= N; i++) in { - intMinn =INF; to intv =-1; + //find the minimum value for the lowcost array that is not included in MST - for(intj =1; J <= N; J + +) the { * if(Mst[j]! =-1&& Lowcost[j] <Minn) $ {Panax Notoginsengv =J; -Minn =Lowcost[j]; the } + } A if(V! =-1)//V=-1 indicates that the smallest edge is not found, the{//v indicates the shortest point of the current distance to MST + //printf ("%d%d%d\n", Mst[v], V, Lowcost[v]);//Output Path -MST[V] =-1; $Sum_mst + =Lowcost[v]; $ for(intj =1; J <= N; J + +)//update the shortest edge - { - if(Mst[j]! =-1&& Lowcost[j] >Map[v][j]) the { -LOWCOST[J] =Map[v][j];WuyiMST[J] =v; the } - } Wu } - } About //printf ("Weight of MST is%d\n", sum_mst); $cout<<sum_mst<<Endl; - } - intMain () - { ACIN >>T; + while(t--) the { -CIN >>N; $ for(inti =1; I <= N; i++) Cin >>A[i]; the for(inti =1; I <= N; i++) the { the for(intj=1; J <= N; J + +) the { -CIN >>Map[i][j]; in if(i = = j)Continue; theMAP[I][J] + = A[i] + a[j];//by adding the weights of the two endpoints to the edges, it turns into a bare MST topic. the } About } thePrim1); the } the return 0; +}
ZOJ-1586 QS Network---minimum spanning tree prim