Description
farmer John was chosen as the mayor of their town. One of
his campaign promises is to build the Internet in the town and connect to all the farms. Of course, he needs your help.
John had arranged a high-speed network line for his farm, and he wanted to share the line with other farms. In order to use the smallest consumption, he wants to lay the shortest fiber to connect all the farms.
you will be given a list of connection costs between farms, and you must find the shortest possible solution for connecting all farms and using the fiber.
Input
This problem contains multiple sets of test data. The
first behavior m represents a group of m test data.
number of first behavior farms per set of data, N (3<=n<=100). The
next is a n*n matrix that represents the distance between each farm. (The distance between farms is less than 100000)
Output for
each set of data has only one export, which contains the minimum length of the fiber connected to each farm.
Sample Input
1 4 0 4 9 4 0 8 9 8 0 (0)
sample Output
Source
Usaco & Data structure and algorithm design P89
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include < cstring> #include <ctime> #include <cmath> #define MX 1<<30 #define MXN 100+10 #define LOC using NA
Mespace std;
int m,n;
int MP[MXN][MXN];
int DS[MXN];
int NC[MXN];
int Prim () {ds[1]=0;
for (int i=2;i<=n;++i) {ds[i]=mp[1][i];
Nc[i]=1;
int tot=0;
for (int i=1;i<=n-1;++i) {int min=mx,nd=0;
for (int j=1;j<=n;++j) if (Ds[j]&&min>ds[j]) {min=ds[j];
Nd=j;
} if (!nd) break;
Tot+=min;
ds[nd]=0;
for (int j=1;j<=n;++j) if (Ds[j]&&ds[j]>mp[nd][j]) {ds[j]=mp[nd][j];
Nc[j]=nd;
} return tot; int main () {#ifdef loc freopen ("bulid.in", "R", stdin);
Freopen ("Bulid.out", "w", stdout);
#endif scanf ("%d", &m);
for (int i=1;i<=m;++i) {scanf ("%d", &n);
for (int j=1;j<=n;++j) for (int k=1;k<=n;++k) {scanf ("%d", &mp[j][k]);
if (!mp[j][k]) mp[j][k]=mx;
printf ("%d\n", Prim ());
return 0;
}