高速公路
(highway.pas)
问题描述:
现在政府计划在某个区域内的的城市间架设高速公路,以使任意两个城市间能够直接或间接到达,怎样修路,费用最小。
输入文件: highway.in
第一行一个整数 n(n<=100)表示城市数目。第二行至第n+1行每行两个数xi,yi(0<=xi,yi<=100)表示第i个城市的坐标;
输出文件:highway.out
输出最小费用。(结果保留两位小数)
输入样例:
3
1 1
1 2
1 3
输出样例:
2.00
很基础的图论题,最小生成树,用prim就行了
const maxn=100; type arr=record x:longint; y:longint; end; var n:longint; total:real; a:array[1..maxn] of arr; h:array[1..maxn] of boolean; map:array[1..maxn,1..maxn] of real; dist:array[1..maxn] of real; procedure init; var i,j:longint; begin assign(input,'highway.in'); assign(output,'highway.out'); reset(input); rewrite(output); fillchar(map,sizeof(map),0); readln(n); for i:=1 to n do readln(a[i].x,a[i].y); for i:=1 to n do for j:=1 to n do begin map[i,j]:=sqrt(sqr(a[i].x-a[j].x)+sqr(a[i].y-a[j].y)); end; end; procedure prim; var i,j,p:longint; min:real; begin for i:=1 to n do dist[i]:=1e10; fillchar(h,sizeof(h),false); dist[1]:=0;h[1]:=true; for i:=2 to n do dist[i]:=map[1,i]; for i:=1 to n-1 do begin min:=1e10;p:=0; for j:=1 to n do if (h[j]=false) and (dist[j]<min) then begin min:=dist[j]; p:=j; end; h[p]:=true; total:=total+dist[p]; for j:=1 to n do begin if (h[j]=false) and (map[p,j]<dist[j]) then dist[j]:=map[p,j]; end; end; end; procedure main; begin prim; writeln(total:0:2); end; procedure outit; begin close(input); close(output); end; begin init; main; outit; end.