# USA 3.1 Agri-Net 最短网络 解题报告

Agri-Net
Russ Cox
Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course.

Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms.

Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm.

The distance between any two farms will not exceed 100,000.

PROGRAM NAME: agrinet
INPUT FORMAT
Line 1:  The number of farms, N (3 <= N <= 100).
Line 2..end:  The subsequent lines contain the N x N connectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.

SAMPLE INPUT (file agrinet.in)
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

OUTPUT FORMAT
The single output contains the integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.

SAMPLE OUTPUT (file agrinet.out)
28

PROGRAM NAME: agrinet

INPUT FORMAT:

(file agrinet.in)

OUTPUT FORMAT:

(file agrinet.out)

SAMPLE INPUT
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
SAMPLE OUTPUT
28

======================= 华丽的分割线 =======================
这一题就是最小生成树的问题, 说来复杂… 自己看数据结构吧..

/*
LANG: C
ID: zqy11001
PROG: agrinet
*/
#include <stdio.h>
#define getint(i) scanf(%d, &i)
#define MAX 100
#define INF 1e6

int map[MAX][MAX];
int visited[MAX];
int path[MAX];

int main(void)
{
int n;
int i, j, k;
int min, m, tot = 0;
freopen(agrinet.in, r, stdin);
freopen(agrinet.out, w, stdout);
getint(n);
for(i = 0; i < n; i++){
for(j = 0; j < n; j++){
getint(map[i][j]);
}
}

for(i = 0; i < n; i++){
path[i] = map[0][i];
}
visited[0] = 1;
for(i = 1; i < n; i++){
min = INF;
for(j = 0; j < n; j++){
if(!visited[j] && min > path[j]){
min = path[j];
m = j;
}
}
visited[m] = 1;
tot += min;
for(j = 0; j < n; j++){
if(visited[j] == 0 && map[m][j] < path[j]){
path[j] = map[m][j];
}
}
}
printf(%d\\n, tot);
return 0;
}