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

【CF20C】Dijkstra?(DIJKSTRA+HEAP)

时间:2016-06-02 21:39:10      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:

没什么可以说的

做dijk+heap模板吧

以后考试时候看情况选择SFPA和DIJKSTRA

技术分享
  1 const oo=110000000000;
  2 var vet,next,len,w:array[1..2100000]of longint;
  3     dis:array[1..1100000]of int64;
  4     a:array[1..1100000]of int64;
  5     b:array[1..1100000]of longint;
  6     inq:array[1..1000000]of boolean;
  7     head:array[1..1000000]of longint;
  8     n,m,tot,i,x,y,z,tt:longint;
  9 
 10 procedure add(a,b,c:longint);
 11 begin
 12  inc(tot);
 13  next[tot]:=head[a];
 14  vet[tot]:=b;
 15  len[tot]:=c;
 16  head[a]:=tot;
 17 end;
 18 
 19 procedure swap(var x,y:int64);
 20 var t:int64;
 21 begin
 22  t:=x; x:=y; y:=t;
 23 end;
 24 
 25 procedure shiftup(k,m:longint);
 26 begin
 27  while (k>1)and(a[k]<a[k div 2]) do
 28  begin
 29   swap(a[k],a[k div 2]);
 30   tt:=b[k]; b[k]:=b[k div 2]; b[k div 2]:=tt;
 31   k:=k div 2;
 32  end;
 33 end;
 34 
 35 procedure shiftdown(k,m:longint);
 36 var t:longint;
 37 begin
 38 
 39  while k+k<=m do
 40  begin
 41   t:=k+k;
 42   if (t+1<=m)and(a[t+1]<a[t]) then inc(t);
 43   if a[k]>a[t] then
 44   begin
 45    swap(a[k],a[t]);
 46    tt:=b[k]; b[k]:=b[t]; b[t]:=tt;
 47    k:=t;
 48   end
 49    else break;
 50  end;
 51 end;
 52 
 53 procedure print;
 54 var x,m,i,e,v:longint;
 55 begin
 56  x:=n; m:=1; w[1]:=n;
 57  while x<>1 do
 58  begin
 59   e:=head[x];
 60   while e<>0 do
 61   begin
 62    v:=vet[e];
 63    if dis[v]+len[e]=dis[x] then
 64    begin
 65     inc(m); w[m]:=v;
 66     x:=v;
 67     break;
 68    end;
 69    e:=next[e];
 70   end;
 71  end;
 72  for i:=m downto 2 do write(w[i], );
 73  write(w[1]);
 74 end;
 75 
 76 procedure dijkstra;
 77 var m,u,e,v:longint;
 78 begin
 79  fillchar(dis,sizeof(dis),$7f);
 80  fillchar(inq,sizeof(inq),false);
 81  m:=1; a[1]:=0; b[1]:=1; dis[1]:=0;
 82  while a[1]<oo do
 83  begin
 84   u:=b[1]; a[1]:=oo; shiftdown(1,m);
 85   if inq[u] then continue;
 86   e:=head[u]; inq[u]:=true;
 87   while e<>0 do
 88   begin
 89    v:=vet[e];
 90    if inq[v] then begin e:=next[e]; continue; end;
 91    if dis[u]+len[e]<dis[v] then
 92    begin
 93     dis[v]:=dis[u]+len[e];
 94     inc(m); a[m]:=dis[v]; b[m]:=v;
 95     shiftup(m,m);
 96    end;
 97    e:=next[e];
 98   end;
 99  end;
100 
101  if dis[n]>oo then writeln(-1)
102   else print;
103 end;
104 
105 begin
106  //assign(input,1.in); reset(input);
107  //assign(output,1.out); rewrite(output);
108  readln(n,m);
109  for i:=1 to m do
110  begin
111   readln(x,y,z);
112   add(x,y,z);
113   add(y,x,z);
114  end;
115  dijkstra;
116  //close(input);
117  //close(output);
118 end.
View Code

 

【CF20C】Dijkstra?(DIJKSTRA+HEAP)

标签:

原文地址:http://www.cnblogs.com/myx12345/p/5554215.html

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