题目:
题目描述
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过了。三种情况模拟。
代码:
var f,a:array[0..100001] of int64;
i,n:longint;
procedure bfs;
var h,t,x:longint;
c:array[0..100001] of boolean;
s:array[0..100001] of int64;
begin
fillchar(c,sizeof(c),true);
fillchar(s,sizeof(s),#0);
fillchar(f,sizeof(f),#0);
h:=1; t:=1; c[a[1]]:=false; f[a[1]]:=1; s[1]:=a[1];
while (h<=t) do
begin
x:=s[h];
if x=n then exit;
if c[a[x]] then
begin
inc(t);
c[a[x]]:=false;
s[t]:=a[x];
f[a[x]]:=f[x]+1;
end;
if (c[x+1])and(x<n) then
begin
inc(t);
c[x+1]:=false;
s[t]:=x+1;
f[x+1]:=f[x]+1;
end;
if (c[x-1])and(x>0) then
begin
inc(t);
c[x-1]:=false;
s[t]:=x-1;
f[x-1]:=f[x]+1;
end;
inc(h);
end;
end;
begin
assign(input,'walk.in');
assign(output,'walk.out');
reset(input);
rewrite(output);
read(n);
if n=1 then begin write(0); halt; end;
for i:=1 to n do read(a[i]);
bfs;
write(f[n]);
close(input);
CLOSE(output);
end.