码迷,mamicode.com
首页 > 其他好文 > 详细

最小生成树kruscal+并查集

时间:2015-04-01 21:51:26      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:

program as;
type
  t1     =record
  x,y,h  :longint;
end;
var
  n,m,s,i:longint;
  a      :array[1..1000000] of t1;
  f      :array[0..1000000] of longint;
  bool   :array[1..1000,1..1000] of boolean;
  sum    :longint;
  totel  :longint;
function find(x:longint):longint;
begin
  if x<>f[x] then
    begin
      f[x]:=find(f[x]);
      exit(f[x]);
    end
  else
  exit(x);
end;
procedure kuai(l,r:longint);
var
  i,j,x     :longint;
  y         :t1;
begin
  i:=l; j:=r;
  x:=a[(l+r) div 2].h;
  repeat
    while a[i].h<x do inc(i);
    while a[j].h>x do dec(j);
    if i<=j then
      begin
        y:=a[i];
        a[i]:=a[j];
        a[j]:=y;
        inc(i);
        dec(j);
      end;
  until i>j;
  if i<r then kuai(i,r);
  if l<j then kuai(l,j);
end;
procedure duru;
var
  i,j,x1  :longint;
begin
  read(n);
  s:=0;
  fillchar(a,sizeof(a),0);
  fillchar(bool,sizeof(bool),true);
  for i:=1 to n do
    for j:=1 to n do
     begin
       read(x1);
       if (i<>j)and(bool[i,j]) then
       begin
         inc(s);
         a[s].x:=i;
         a[s].y:=j;
         a[s].h:=x1;
         bool[i,j]:=false;
         bool[j,i]:=false;
       end;
     end;
end;
procedure kruscal;
var
  x,y,i,j :longint;
begin
  for i:=1 to s do
    f[i]:=i;
  for i:=1 to s do
    begin
      x:=find(a[i].x);
      y:=find(a[i].y);
      if x<>y then
        begin
          f[x]:=y;
          inc(sum,a[i].h);
          inc(totel);
        end;
      if totel=n-1 then
        exit;
    end;
end;
begin
  duru;
  kuai(1,s);
  kruscal;
  writeln(sum);

end.

最小生成树kruscal+并查集

标签:

原文地址:http://blog.csdn.net/bugall/article/details/44813931

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!