题意:数轴上,给定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