DP的最短路径问题

来源:百度知道 编辑:UC知道 时间:2024/05/21 11:13:59
DP的最短路径问题的Pascal代码。
要DP的!!!

DP是指将状态保存下来的一种记忆化搜索,Dijkstra 算法是DP的一种

下面是Dijkstra 算法:

基本思想是:设置一个顶点的集合s,并不断地扩充这个集合,一个顶点属于集合s当且仅当从源点到该点的路径已求出。开始时s中仅有源点,并且调整非s中点的最短路径长度,找当前最短路径点,将其加入到集合s,直到终点在s中。

program zudlouj;
const n=6;max=10000 ;
cost:array[1..6,1..6] of real=((0,50,10,max,45,max),(max,0
,15,max,10,max),(20,max,0,15,max,max),(max,20,max,0,35,max),(
max,max,max,30,0,max),(max,max,max,3,max,0));
var dist:array[1..n] of real;
path,p:array[1..n] of 1..n;
first,tail,u:1..n;
s:set of 1..n;
i,j,y,m:integer;
min:real;
begin
read(first,tail);
for i:=1 to n do dist[i]:=max;
dist[first]:=0;
s:=[first]; u:=first;
while u<>tail do
begin
for j:= 1 to n do
if not(j in s) and (dist[u]+cost[u,j]<dist[j]) then
begin dist[j]:=dist[u]+cost[u,j];path[j]:=u end;
min:=max;
for j:=1 to n do
if not(j in s) and (dist