bzoj 1646 bfs

7 篇文章 0 订阅

题意:数轴上,给定n和pos,起点为n,终点为pos,有两种移动方式:(1)每次向前或后移动一个单位长度(2)从x瞬移到2*x,每种移动均耗费1s,求从n到pos的最少时间

裸bfs...,注意能到pos的位置只有pos-1、pos+1、pos/2,所以bfs的时候到达点的范围最大为pos+1,限制一下,不然一直RE...

var
        n,pos,m         :longint;
        que,ans         :array[0..200010] of longint;
procedure bfs;
var
        h,tl,cur:longint;
begin
   fillchar(ans,sizeof(ans),127);
   h:=0; tl:=1; que[1]:=n; ans[n]:=0;
   while (h<>tl) do
   begin
      h:=h mod 200005+1;
      cur:=que[h];
      if (cur+1<=m) and (ans[cur+1]>ans[cur]+1) then
      begin
         ans[cur+1]:=ans[cur]+1;
         tl:=tl mod 200005+1;
         que[tl]:=cur+1;
         if cur+1=pos then exit;
      end;
      if (cur-1<=m) and (ans[cur-1]>ans[cur]+1) then
      begin
         ans[cur-1]:=ans[cur]+1;
         tl:=tl mod 200005+1;
         que[tl]:=cur-1;
         if cur-1=pos then exit;
      end;
      if (2*cur<=m) and (ans[2*cur]>ans[cur]+1) then
      begin
         ans[2*cur]:=ans[cur]+1;
         tl:=tl mod 200005+1;
         que[tl]:=2*cur;
         if 2*cur=pos then exit;
      end;
   end;
end;

begin
   read(n,pos);
   if n>pos then m:=n+1 else m:=pos+1;
   bfs;
   writeln(ans[pos]);
end.
——by Eirlys

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值