Topic Description
The 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.
The distance between two farms will not exceed 100000 INPUT FORMAT
First line: |
Number of farms, N (3<=n<=100). |
Second line ... End: |
The subsequent rows contain a n*n matrix that represents the distance between each farm. In theory, they are n rows, each of which consists of n-delimited numbers of spaces, in fact, they are limited to 80 characters, so some rows are followed by others. Of course, the diagonal will be 0, because there will be no line from the first farm to itself. |
SAMPLE INPUT (file agrinet.in)
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
OUTPUT FORMAT
There is only one output, which contains the minimum length of the fiber attached to each farm.
SAMPLE OUTPUT (file agrinet.out)
28
Solving
This problem is a very classic minimal spanning tree. The following is the code for the prim algorithm.
var
n,i,j,k,min,sum:longint;
A:array[1..1000,1..1000]of Longint;
D:array[1..1000]of Longint;
Procedure Prim;
Begin
Sum:=0;
For I:=1 to n do d[i]:=a[1,i];
For j:=2 to n do
begin
Min:=maxlongint;
For I:=1 to n do
if (d[i]<min) and (d[i]<>0) then
begin
Min:=d[i];
k:=i;
End;
SUM:=SUM+D[K];
d[k]:=0;
For I:=1 to n do
if (A[k,i]<d[i]) and (i<>k) then d[i]:=a[k,i];
End;
End;
Begin
READLN (n);
For I:=1 to N does for
j:=1 to n do
begin
Read (A[I,J);
if (i<>j) and (a[i,j]=0) then a[i,j]:=maxlongint;
End;
Prim;
Writeln (sum);
End.
I hope you learn the graph theory.