I and OI
Past...

题意:给出一个带权矩阵,一开始人在第1行,只能向下,左,右三个方向走,走到每一个点(i,j)都要支付a[i,j]的费用,

求一条从第1行到第n行的最小费用路径.

分析:DP,f[i,j]表示到(i,j)时的最优值.f[i,j]=min(f[i-1,j],f[i,j+1],f[i,j-1]).

用d[i,j]记录走的方向.注意更新顺序.

code:

const oo=2100000000;
var   f,cost,d:array[0..110,0..510] of longint;
      res:array[0..50000] of longint;
      up,left,right,ans:longint;
      n,m,i,j,pos,from,x,y,tot:longint;

begin
      readln(n,m);
      for i:=1 to n do
      begin
            for j:=1 to m do read(cost[i,j]);
            readln;
      end;

      for i:=1 to m do f[1,i]:=cost[1,i];
      for i:=2 to n do
      begin
            f[i,1]:=f[i-1,1]+cost[i,1];
            d[i,1]:=1;
            for j:=2 to m do
            begin
                  f[i,j]:=f[i-1,j]+cost[i,j];
                  d[i,j]:=1;
                  if f[i,j]>f[i,j-1]+cost[i,j] then
                  begin
                        f[i,j]:=f[i,j-1]+cost[i,j];
                        d[i,j]:=2;
                  end;
            end;

            for j:=m-1 downto 1 do
            if f[i,j]>f[i,j+1]+cost[i,j] then
            begin
                  f[i,j]:=f[i,j+1]+cost[i,j];
                  d[i,j]:=3;
            end;

      end;

      ans:=oo;
      for i:=1 to m do
      if f[n,i]<ans then
      begin
            ans:=f[n,i];
            pos:=i;
      end;

      x:=n; y:=pos;
      while x<>1 do
      begin
            inc(tot);
            res[tot]:=y;
            case d[x,y] of
            1:dec(x);
            2:dec(y);
            3:inc(y);
            end;
      end;
      inc(tot); res[tot]:=y;
      for i:=tot downto 1 do writeln(res[i]);
end.
posted on 2011-08-12 16:37  exponent  阅读(470)  评论(0编辑  收藏  举报