【dp】汽车加油行驶问题

来源:互联网 发布:舞台设计软件 编辑:程序博客网 时间:2024/06/10 01:40

问题描述:

 给定一个N*N 的方形网格,设其左上角为起点,坐标为(1,1),X 轴向右为正,Y 轴向下  为正,每个方格边长为1。一辆汽车从起点出发驶向右下角终点,其坐标为(N,N)。在若  干个网格交叉点处,设置了油库,可供汽车在行驶途中加油。汽车在行驶过程中应遵守如下  规则:
  (1)汽车只能沿网格边行驶,装满油后能行驶K 条网格边。出发时汽车已装满油,在起点  与终点处不设油库。
  (2)当汽车行驶经过一条网格边时,若其X 坐标或Y 坐标减小,则应付费用B,否则免付费  用。
  (3)汽车在行驶过程中遇油库则应加满油并付加油费用A。
  (4)在需要时可在网格点处增设油库,并付增设油库费用C(不含加油费用A)。
  (5)(1)~(4)中的各数N、K、A、B、C均为正整数。

编程任务:

 求汽车从起点出发到达终点的一条所付费用最少的行驶路线。

数据输入:

 输入数据。第一行是N,K,A,B,C的值,2 <= N <= 100,2 <= K <= 10。第二行起是一  个N*N 的0-1方阵,每行N 个值,至N+1行结束。方阵的第i行第j 列处的值为1 表示在网格交  叉点(i,j)处设置了一个油库,为0 时表示未设油库。各行相邻的2 个数以空格分隔。

结果输出:

 将找到的最优行驶路线所需的费用,即最小费用输出.

样例:

 9 3 2 3 6
 0 0 0 0 1 0 0 0 0
 0 0 0 1 0 1 1 0 0
 1 0 1 0 0 0 0 1 0
 0 0 0 0 0 1 0 0 1
 1 0 0 1 0 0 1 0 0
 0 1 0 0 0 0 0 1 0
 0 0 0 0 1 0 0 0 1
 1 0 0 1 0 0 0 1 0
 0 1 0 0 0 0 0 0 0

12

核心思想:

 spfa或者dp,四个方向,有油没油。

const maxn=100;var n,go,cost,gocost,build:longint; map:array [0..maxn,0..maxn] of longint; work:array [0..maxn,0..maxn,0..12] of longint; s:array[0..4,0..3] of longint;procedure init;var i,j:longint;begin readln(n,go,cost,gocost,build); fori:=0 to n-1 do begin  for j:=0 to n-1 do read(map[i,j]);  readln; end; s[0,0]:=-1; s[0,1]:=0; s[0,2]:=0; s[1,0]:=0; s[1,1]:=-1; s[1,2]:=0; s[2,0]:=1; s[2,1]:=0; s[2,2]:=gocost; s[3,0]:=0; s[3,1]:=1; s[3,2]:=gocost;end;procedure main;var i,y,j,z,p,q,min,x:longint;begin fori:=0 to n-1 do for j:=0 to n-1 do for z:=0 to go+1 do work[i,j,z]:=1000000; fori:=0 to go do work[0,0,i]:=0; y:=1; while y<>0 do begin  y:=0;  for i:=0 to n-1 do   begin    for j:=0 to n-1 do     begin      if (i<>0) or (j<>0) then       begin        for p:=0 to go do         begin          min:=1000000;          for q:=0 to 3 do           begin            if (i=0) and (q=0) thencontinue;            if (j=0) and (q=1) then continue;            if (i=n-1) and (q=2) then continue;            if (j=n-1) and (q=3) then continue;             if(work[i+s[q,0],j+s[q,1],p+1]+s[q,2]<mint) henmin:=work[i+s[q,0],j+s[q,1],p+1]+s[q,2];           end;          if min<1000000 then           begin            if work[i,j,p]>min+cost*map[i,j] then inc(y);            work[i,j,p]:=min;            if map[i,j]=1 then              begin               inc(work[i,j,0],cost);               for x:=1 to go dowork[i,j,x]:=work[i,j,0];               break;              end;           end          else           begin            work[i,j,p]:=work[i,j,0]+cost+build;            for x:=p+1 to go do work[i,j,x]:=work[i,j,p];            break;           end;         end;       end;     end;   end; end;end;begin assign(input,'p39.in'); reset(input); assign(output,'p39.out'); rewrite(output); init; main; writeln(work[n-1,n-1,0]); close(input); close(output);end.
题目来源:《算法设计与分析》第三章动态规划