Describe
Recently, little hi is very fond of playing a game simulation of the city opened a new mod, in this mod, the player can have more than one city!
But the problem also follows--Little hi now has n cities in hand, and it is known that the cost of building roads between any two cities in these n cities, little hi would like to know that the minimum cost would allow any two cities to reach each other through the roads they built (assuming a, B, c three cities, Only the road between AB and BC can be built, and the two roads will be connected by AC.
Input
Each test point (input file) has and has only one set of test data.
In a set of test data:
The 1th behavior is 1 integer n, which indicates the number of cities owned by small hi.
The next n rows, for a n*n matrix A, describe the cost of building a road between any two cities, with the number of J in line I being AIJ, which represents the cost of building roads between the city of Block I and Block J.
For 100% of data, satisfies n<=10^3, for any I, satisfies aii=0, for any I, J satisfies Aij=aji, 0<aij<10^4.
Output
For each set of test data, Output 1 integer ans, indicating that in order for any two cities to reach each other at least the required construction costs through the roads they build.
Sample Input
Sample Output
4178
Test Instructions Description:
Enter the number of cities and the N*n matrix
Calculation and output allows any two cities to reach each other at least the required construction costs through the roads they build
Problem Solving Ideas:
A typical minimum spanning tree, based on the format of the data, can be used with the prim algorithm. The main idea of the prim algorithm is to select the nearest node of the spanning tree and then update the new node to the distance from each node that has not been added to the tree, making it easy to find the closest node to the spanning tree next time.
Code implementation:
1#include <stdio.h>2#include <string.h>3 inte[1100][1100],book[1100],dis[1100];4 Const intinf=99999999;5 intMain ()6 {7 intn,i,j,k,c,sum,min;8 while(SCANF ("%d", &n)! =EOF)9 {Ten for(i=1; i<=n;i++) One for(j=1; j<=n;j++) Ascanf"%d",&e[i][j]); - for(i=1; i<=n;i++) -dis[i]=e[1][i]; the -memset (book,0,sizeof(book)); -book[1]=1; -C=1; +sum=0; - while(C <N) + { Amin=inf; at for(j=0, i=1; i<=n;i++) - { - if(!book[i] && dis[i] < min)//Note the relationship that is and - { -min=Dis[i]; -j=i; in } - } tobook[j]=1; +C++; -Sum + =Dis[j]; the for(k=1; k<=n;k++) * { $ if(!book[k] && dis[k] >E[j][k])Panax Notoginsengdis[k]=E[j][k]; - } the } +printf"%d\n", sum); A } the return 0; +}
Error-Prone analysis:
1. Note that when searching for the closest node to the spanning tree, the condition is determined and
Prim algorithm of minimum spanning tree