Uploaded
Zhang yuncong
The concept of this question is not very complex. First, find the minimum spanning tree between the buildings, and then sort the cost of connecting the buildings with the outside world, adding the minimum cost and the Minimum Spanning Tree weight is the minimum cost. You can use the prim algorithm to find the Minimum Spanning Tree and sort buildings in a quick sort;
Although the idea for this question is very simple, WA has been used for many times. I don't know if it is a system problem or something. I searched someone else's code on the Internet and submitted it to WA, at first, the code was able to communicate with each other. Later, I tested the code step by step. I initialized map [] [] with memset and started wa, and changed it to AC, I don't know why. Can't I use memset to initialize a two-dimensional array? You still cannot use memset to initialize the maximum value. Pay attention to it later. You can also use a loop to initialize map;
The following is the code;
# Include <cstdio> # include <cstring> # include <algorithm> using namespace STD; const int max = 0x3f3f3f3f; const int maxn = 500 + 20; int map [maxn] [maxn], visit [maxn], low [maxn]; int V, E; int prim () {int POs, I, j, Min, sum = 0; memset (visit, 0, sizeof (visit); // initialize the visit array visit [1] = 1; // Pos = 1 from the first vertex; // mark and record this point for (I = 1; I <= V; I ++) low [I] = map [POS] [I]; // use the low array to record the weight value for (I = 1; I <v; I ++) // The first vertex has been done and n-1 times are required; {min = max; // assign min to the initial value (J = 1; j <= V; j ++) {If (visit [J] = 0 & low [J]! = 0 & low [J] <min) // compare the weight value {min = low [J]; Pos = J; // point with the minimum record weight, next time starting from this point} sum + = min; // The sum of the recorded weights and visit [POS] = 1; // mark the access for (j = 1; j <= V; j ++) // access the next vertex {If (visit [J] = 0 & low [J]> map [POS] [J]) low [J] = map [POS] [J] ;}return sum ;}int main () {int N, A, B, C, I, J; int R [maxn]; scanf ("% d", & N); While (n --) {scanf ("% d", & V, & E ); for (I = 1; I <= V; I ++) for (j = 1; j <= I; j ++) map [I] [J] = map [J] [I] = max; // memset (MAP, 0, sizeof (MAP )); // This Is Where wa is used many times. For (I = 1; I <= E; I ++) {scanf ("% d", &, & B, & C); map [a] [B] = map [B] [a] = C;} For (j = 1; j <= V; j ++) scanf ("% d", & R [J]); sort (R + 1, R + V + 1); printf ("% d \ n ", prim () + R [1]);} return 0 ;}
Here we can also see that someone else can directly sort by insert and compare a minimum value;
min=MAX;for(i=1;i<=v;i++){scanf("%d",&a);if(a<min)min=a;}
It may be faster to process some small data, and memory is saved here, and sometimes it needs flexible processing.