您的位置:首页 > 其它

JZOJ 3.25 1422——【汕头市选2012初中组】步行(walk)

2017-03-25 14:33 281 查看
题目描述

ftiasch 又开发了一个奇怪的游戏,这个游戏是这样的:有N 个格子排成一列,每个格子上有一个数

字,第i 个格子的数字记为Ai。这个游戏有2 种操作:

如果现在在第i 个格子,则可以跳到第Ai 个格子。

把某个Ai 增加或减少1。

nm 开始在第1 个格子,他需要走到第N 个格子才能通关。现在他已经头昏脑涨啦,需要你帮助他

求出,从起点到终点最少需要多少次操作。

输入

第1 行,1 个整数N。第2 行,N 个整数Ai。

输出

第1 行,1 个整数,表示最少的操作次数。

样例输入

5

3 4 2 5 3

样例输出

3

数据范围

• 对于30% 的数据,1<=  N <=  10。

• 对于60% 的数据,1<=   N <=  1 000。

• 对于100% 的数据,1  <= N<=   100000,1 <=  Ai <=  N。

其实这是一道bfs题。

用v数组来存储有没有走过;用father数组来记录到i最少的操作数;用state数组来记录i到了那个位置。

然后再三种情况
4000
模拟

代码如下:

var father,a:array[0..100001]of int64;
n,i:longint;

procedure bfs;
var head,tail,x:longint;
v,state:array[0..100001]of int64;
begin
fillchar(v,sizeof(v),#0);
fillchar(state,sizeof(state),#0);
fillchar(father,sizeof(father),#0);
head:=1;
tail:=1;
v[a[1]]:=1;
father[a[1]]:=1;
state[1]:=a[1];
while (head<=tail) do
begin
x:=state[head];
if x=n then exit;
if v[a[x]]=0 then
begin
inc(tail);
v[a[x]]:=1;
state[tail]:=a[x];
father[a[x]]:=father[x]+1;
end;
if (v[x+1]=0)and(x<n) then
begin
inc(tail);
v[x+1]:=1;
state[tail]:=x+1;
father[x+1]:=father[x]+1;
end;
if (v[x-1]=0)and(x>0) then
begin
inc(tail);
v[x-1]:=1;
state[tail]:=x-1;
father[x-1]:=father[x]+1;
end;
inc(head);
end;
end;

begin
assign(input,'walk.in');
assign(output,'walk.out');
reset(input);
rewrite(output);
readln(n);
for i:=1 to n do read(a[i]);
if i=1 then begin write(0); halt; end;
bfs;
writeln(father
);
close(input);
close(output);
end.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: