Topic 1: Minimum spanning tree one · Prim algorithm time limit:10000msSingle Point time limit:1000msMemory Limit:256MBDescribe
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.
Tip: I don't know why prim algorithm and Dijstra algorithm are like σ (っ°д°;) our store. 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
#include <stdio.h> #include <string.h> #include <iostream> #include <string> #include < algorithm> #define INF 999999999#define n 1001using namespace std;int map[n][n];bool vis[n];int dis[n];int N, sum;void p Rim () {sum=0;//minimum spanning tree weights and initialization 0 int mm; int I, J; Memset (Vis, false, sizeof (VIS)); for (i=0; i<n; i++) {dis[i]=map[0][i]; } vis[0]=true; int POS; for (i=0; i<n-1; i++) {mm=inf; for (j=0; j<n; J + +) {if (Vis[j]==false && dis[j]<mm) {mm=dis[j]; Pos=j; }} sum+=mm; Vis[pos]=true; for (j=0; j<n; J + +) {if (Vis[j]==false && Dis[j]>map[j][pos]) { Dis[j]=map[j][pos]; }}} printf ("%d\n", sum);} int main () {int i, J; scanf ("%d", &n); For (i=0, i<n; i++) {for (j=0; j<n; J + +) { scanf ("%d", &map[i][j]); }} prim (); return 0;}
Hihocoder Hiho The 26th week minimum spanning tree one · (Prim algorithm)