基于matlab的spfa算法,关于最短路径的程序 spfa算法

不管怎么说,得到了自己的一个SPFA程序

{

TASK:butter

LANG:PASCAL

}

program butter;

const

maxn=800;

maxq=maxn shl 1;

var

n,p,c:integer;

map:array[1..maxn,1..maxn]of integer;

dis:array[1..maxn,1..maxn] of longint;

cowin:array[0..maxn] of integer;

connect:array[1..maxn,0..maxn] of integer;

procedure init;

var

i,x,y,distance:integer;

begin

assign(input,'butter.in');reset(input);

fillchar(cowin,sizeof(cowin),0);

fillchar(connect,sizeof(connect),0);

fillchar(map,sizeof(map),255);

readln(n,p,c);

for i:=1 to n do

begin

inc(cowin[0]);

readln(cowin[cowin[0]]);

end;

for i:=1 to c do

begin

readln(x,y,distance);

if (map[x,y]=-1)or (distance

begin

map[x,y]:=distance;

map[y,x]:=distance;

end;

inc(connect[x,0]);

connect[x,connect[x,0]]:=y;

inc(connect[y,0]);

connect[y,connect[y,0]]:=x;

end;

for i:=1 to p do

begin

map[i,i]:=0;

dis[i,i]:=0;

end;

close(input);

end;

procedure spfa(v0:integer);

var

i,now,open,close:integer;

queue:array[1..maxq] of integer;

inqueue:array[1..maxn] of boolean;

begin

fillchar(inqueue,sizeof(inqueue),0);

fillchar(queue,sizeof(queue),0);

fillchar(dis[v0],sizeof(dis[v0]),255);

dis[v0,v0]:=0;

queue[1]:=v0;

inqueue[v0]:=true;

open:=0;

close:=1;

while close<>open do

begin

inc(open);

if open>maxq then dec(open,maxq);

now:=queue[open];

inqueue[now]:=false;

for i:=1 to connect[now,0] do

if (dis[v0,connect[now,i]]=-1)or(dis[v0,now]+map[now,connect[now,i]]

begin

dis[v0,connect[now,i]]:=dis[v0,now]+map[now,connect[now,i]];

if not inqueue[connect[now,i]] then

begin

inc(close);

if close>maxq then dec(close,maxq);

queue[close]:=connect[now,i];

inqueue[connect[now,i]]:=true;

end;

end;

end;

end;

procedure work;

var

i,j:integer;

min,sum:longint;

begin

assign(output,'butter.out');rewrite(output);

for i:=1 to cowin[0] do

spfa(cowin);

min:=maxlongint;

for i:=1 to p do

begin

sum:=0;

for j:=1 to cowin[0] do

inc(sum,dis[cowin[j],i]);

if min>sum then min:=sum;

end;

writeln(min);

{for i:=1 to p do

begin

for j:=1 to p do

write(dis[i,j],' ');

writeln;

end; }

close(output);

end;

begin

init;

work;

end.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值