【Usaco2009 gold 】修建道路

题意:

求最小生成树

思路:

把他给你的边当做长度为0,然后根据欧几米的距离连边,并查集搞一搞,就好了

程序:

 type
 Point=record
      x,y:longint;
      w:real;
 end;
const
 maxn=1000000;
 maxv=1000;
var
 f,x,y:array [1..maxn] of longint;
 s:array [1..maxv,1..maxv] of boolean;
 a:array [0..maxn] of Point;
 i,j,k,n,m,x1,y1,p:longint;
 ans:real;

function father(x:longint):longint;
begin
 if x<>f[x] then father:=father(f[x])
            else father:=x;
 f[x]:=father;
end;

procedure qsort(l,r:longint);
var
 i,j:longint;
 mid:real;
begin
 i:=l; j:=r;
 mid:=a[(l+r) div 2].w;
 while i<j do
 begin
  while a[i].w<mid do inc(i);
  while a[j].w>mid do dec(j);
  if i<=j then
  begin
   a[0]:=a[i];
   a[i]:=a[j];
   a[j]:=a[0];
   inc(i); dec(j);
  end;
 end;
 if l<j then qsort(l,j);
 if r>i then qsort(i,r);
end;


begin
 readln(n,m);
 for i:=1 to n do
  readln(x[i],y[i]);
 for i:=1 to n do
  f[i]:=i;
 for i:=1 to m do
 begin
  readln(x1,y1);
  f[father(x1)]:=father(y1);
  s[x1,y1]:=true;
  s[y1,x1]:=true;
 end;
 for i:=1 to n-1 do
  for j:=i+1 to n do
   if  not s[i,j] then
                  begin
                   inc(p);
                   a[p].x:=i;
                   a[p].y:=j;
                   a[p].w:=sqrt(sqr(x[i]-x[j])+sqr(y[i]-y[j]));
                  end;
 qsort(1,p);
 for i:=1 to p do
  if father(a[i].x)<>father(a[i].y) then
  begin
   f[father(a[i].x)]:=father(a[i].y);
   ans:=ans+a[i].w;
  end;
 writeln(ans:0:2);
end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值