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

题目描述

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

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

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

  2. 把某个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到了那个位置。
然后再三种情况模拟


代码如下:

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[n]);
  close(input);
  close(output);
end.

转载于:https://www.cnblogs.com/Comfortable/p/8412350.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值