用户ID: 密码: 验证:

登 录

注 册 取回密码

中山教育

中山国际网

中国教育在线

时代财富科技公司 FortuneAge Technology Co., Ltd. 校园博客客服网站(新)

我的资料

Mpq

博客信息

积分:988
等级:4级 lv 4
日志总数:231
发表评论总数:18 ( 查看)
获得评论总数:21
发表留言总数:0
所属学校:三鑫
收藏本站:

最新公告

欢迎光临我的博客!

最新相册

我的日历

最新评论

--游客
好文好文,是您的手笔?如果是您的文章,如果您愿意和我联系,...
还有就是数学不能使用计算器…….......在读初中之前原...
--Mpq
这次似乎不举行冬季长跑……看来在三鑫参加的体育项目最终是以...
--Mpq
看了你的"总结", 挺有针对性的! 相信下学期你一定会有...

RSS


首页 -> 经典算法->用Heap做Dijkstra
用Heap做Dijkstra

程序名:dijkstra

任务: 求出所给无向图(边权非负)的单源最短路.

输入格式:

第一行: 点数N(2 <= N <= 10,000), 边数M(M <= 100,000), 源点S(1 <= S <= N)

以下M, 每行三个整数a, b, c表示点a, b(1 <= a, b <= N)之间连有一条边, 权值为c(0 <= c <= 100,000)

 

Sample Input

6 8 1

1 3 4

1 2 6

3 4 7

6 4 2

2 4 5

3 6 3

4 5 1

3 5 4

 

Sample Output

0

6

4

9

8

7

输出格式:

N: 输出源点到各点的最短路, 到该点不连通则输出-1

 

 

Program Dijkstra_Mpq;

type link=^node;
     node=record
       Num,Cost:Longint;
       Next:link;
     end;

Const Maxn=100001;
      MaxLong=MaxLongint shr 1;

var
  p:link;
  n,m,start:Longint;
  a:array[0..Maxn] of link;
  x,y,Num:array[1..Maxn] of Longint;

procedure swap(i,j:Longint);
procedure f(var i,j:Longint);
var
  Tmp:Longint;
begin
  Tmp:=i;
  i:=j;
  j:=Tmp;
end;

begin
  f(x[i],x[j]);
  f(y[i],y[j]);
  f(Num[y[i]],Num[y[j]]);
end;

procedure down(r:Longint);
var
  i,j:Longint;
begin
  i:=1; j:=i*2;
  while j<=r do
  begin
    if (x[j]>x[j+1]) and (j<r) then inc(j);
    if x[i]>x[j] then
    begin
      swap(i,j);
      i:=j;
      j:=j shl 1;
    end else exit;
  end;
end;

procedure up(n:Longint);
var
  i,j:Longint;
begin
  j:=n; i:=n shr 1;
  while i>0 do
  begin
    if x[j]<x[i] then
    begin
      swap(i,j);
      j:=i;
      i:=i shr 1;
    end else exit;
  end;
end;

procedure init;
var
  i,xx,yy,zz:Longint;
begin
  fillchar(a,sizeof(a),0);
  readln(n,m,start);
  for i:=1 to m do
  begin
    readln(xx,yy,zz);
    new(a[0]);
    a[0]^.Num:=yy;
    a[0]^.Cost:=zz;
    a[0]^.Next:=a[xx];
    a[xx]:=a[0];
    new(a[0]);
    a[0]^.Num:=xx;
    a[0]^.Cost:=zz;
    a[0]^.Next:=a[yy];
    a[yy]:=a[0];
  end;
  for i:=1 to n do
  begin
    x[i]:=MaxLong;
    y[i]:=i;
    Num[i]:=i;
  end;
  x[start]:=0;
  up(start);
end;

procedure Dijkstra;
var
  i,Len,Tmp:Longint;
begin
  Len:=n;
  for i:=1 to n-1 do
  begin
    swap(1,Len);
    down(Len-1);
    if x[Len]=Maxlong then break;
    p:=a[y[Len]];
    while p<>nil do
    begin
      Tmp:=x[Num[y[Len]]]+p^.Cost;
      if Tmp<x[Num[p^.Num]] then
      begin
        x[Num[p^.Num]]:=Tmp;
        up(Num[p^.Num]);
      end;
      p:=p^.Next;
    end;
    dec(Len);
  end;
  for i:=1 to n do
    if x[Num[i]]=MaxLong then writeln(-1) else
                              writeln(x[Num[i]]);
end;

begin

assign(input,'Dijkstra.in'); reset(input);
assign(output,'Dijkstra.out'); rewrite(output);
  init;
  Dijkstra;
close(input); close(output);
end.

网友评论

共 0 页,0 条记录  

用户名:
密码:
您的评论:
正在载入编辑器...
请输入验证码:


发 表 评 论

Mpq-中山教师家园