最小代价问题

来源:互联网 发布:mac装win7 集成显卡 编辑:程序博客网 时间:2024/06/06 19:35

最小代价问题


Description

设有一个n×m(小于100)的方格(如图所示),在方格中去掉某些点,方格中的数字代表距离(为小于100的数,如果为0表示去掉的点),试找出一条从A(左上角)到B(右下角)的路径,经过的距离和为最小(此时称为最小代价),从A出发的方向只能向右,或者向下。

Input

Output

Sample Input

4 4  4 10 7 03 2 2 90 7 0 411 6 12 1

Sample Output

(1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(3,4)->(4,4)
  • var map,dis,g:array[0..101,0..101]of longint; y,x,i,j,t:longint;procedure dg(n,m:longint);begin    if (n<1) or (m<1) then exit;    if g[n,m]=2 then dg(n-1,m)                else dg(n,m-1);    if (n<>x) or (m<>y) then write('(',n,',',m,')->')    else write('(',n,',',m,')');end;begin read(x,y); for i:=1 to x do  begin   for j:=1 to y do    read(map[i,j]);   readln;  end; dis[1,1]:=map[1,1]; for i:=1 to y do  if (dis[1,i-1]<>0) and (map[1,i]<>0) then     begin          dis[1,i]:=map[1,i]+dis[1,i-1];          g[1,i]:=1;//标记路径     end; for i:=1 to x do  if (dis[i-1,1]<>0) and (map[i,1]<>0) then     begin         dis[i,1]:=map[i,1]+dis[i-1,1];         g[i,1]:=2;//标记路径     end; for i:=2 to x do  begin   for j:=2 to y do    begin     if (map[i,j]<>0) then         begin              if (dis[i-1,j]=0) or ((dis[i,j-1]<>0) and (dis[i-1,j]>dis[i,j-1]))                 then begin                         dis[i,j]:=map[i,j]+dis[i,j-1];                         g[i,j]:=1;//标记路径                      end                 else if (dis[i,j-1]=0) or ((dis[i-1,j]<>0) and (dis[i,j-1]>dis[i-1,j])) then                          begin                               dis[i,j]:=map[i,j]+dis[i-1,j];                               g[i,j]:=2;//标记路径                          end;         end;     end;  end; dg(x,y); writeln; write(dis[x,y]-map[x,y]);end.

0 0
原创粉丝点击