Description
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.
Input
The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity 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.
Output
For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.
Sample Input
4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0
Sample Output
28
Source
题目大意
给出n*n的邻接矩阵,求这n个点的最小生成树
思路
因为我比较懒所以最小生成树用了kruskal,写了邻接表+并查集优化
打完发现这是一个稠密图,prim算法可能会更好一些
代码/pas
type
edge=record
x,y,w:longint;
end;
var
a,b,n,i,k:longint;
f,v:array[1..200]of longint;
e:array[1..10000]of edge;
min,ans:longint;
procedure qsort(l,r:longint);
var
x,y,key:longint;
temp:edge;
begin
if l>=r then exit;
x:=l;
y:=r;
key:=e[l+random(r-l+1)].w;
repeat
while (e[x].w<key) do inc(x);
while (e[y].w>key) do dec(y);
if x<=y then
begin
temp:=e[x];
e[x]:=e[y];
e[y]:=temp;
inc(x);
dec(y);
end;
until x>y;
qsort(l,y);
qsort(x,r);
end;
function find(x:longint):longint;
var
y,w,root:longint;
begin
y:=x;
while f[y]<>0 do y:=f[y];
root:=y;
y:=x;
while f[y]<>0 do
begin
w:=f[y];
f[y]:=root;
y:=w;
end;
find:=root;
end;
procedure union(x,y:longint);
begin
if find(x)<>find(y) then
f[x]:=y;
end;
procedure init;
var
i,j:Longint;
begin
readln(n);
for i:=1 to n do
for j:=1 to n do
with e[(i-1)*n+j] do
begin
read(w);
x:=i;
y:=j;
end;
for i:=1 to n do v[i]:=i;
fillchar(f,sizeof(f),0);
ans:=0;
end;
begin
while not seekeof do
begin
init;
qsort(1,n*n);
k:=0;
for i:=1 to n*n-1 do
if k=n then break
else
begin
a:=find(e[i].x);
b:=find(e[i].y);
if a<>b then
begin
ans:=ans+e[i].w;
union(a,b);
inc(k);
end;
end;
writeln(ans);
end;
end.