您的位置:首页 > 其它

一、动态规划(2)奇怪的电梯

2015-07-14 12:28 183 查看
奇怪的电梯

源程序名 LIFT.??? (PAS,C,CPP)

可执行文件名 LIFT.EXE

输入文件名 LIFT. IN

输出文件名 LIFT. OUT

呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,

而且第 i 层楼(1<=i<=N) 上有一个数字 Ki(0<=Ki<=N) 。电梯只有四个按钮:开,关,上,下。

上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。

例如: 3 3 1 2 5 代表了 Ki(K1=3,K2=3,……) ,从一楼开始。在一楼,按“上” 可以到 4

楼,按“ 下” 是不起作用的,因为没有-2 楼。那么,从 A 楼到 B 楼至少要按几次按钮呢?

输入

输入文件共有二行,第一行为三个用空格隔开的正整数,表示 N,A,B(1≤N≤200,

1≤A,B≤N) ,第二行为 N 个用空格隔开的正整数,表示 Ki。

输出

输出文件仅一行,即最少按键次数, 若无法到达,则输出-1。

样例

LIFT.IN

5 1 5

3 3 1 2 5

LIFT.OUT

3

分析:

水题,n多种方法:dp,bfs等等

代码:

var

step,lift:array [1..200] of longint;

i,j,p,n,s,t:longint;

stop:boolean;

begin

assign(input,'lift.in');

assign(output,'lift.out');

reset(input);

rewrite(output);

readln(n,s,t);

for i:=1 to n do

begin

step[i]:=-1;

read(lift[i]);

end;

step[s]:=0;

p:=0;

stop:=true;

while (step[t]=-1) and stop do

begin

stop:=false;

for i:=1 to n do

if step[i]=p then

begin

j:=i+lift[i];

if (j<=n) and (step[j]=-1) then

begin

step[j]:=p+1;

stop:=true;

end;

j:=i-lift[i];

if (j>0) and (step[j]=-1) then

begin

step[j]:=p+1;

stop:=true;

end;

end;

inc(p);

end;

writeln(step[t]);

close(input);

close(output);

end.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: