题目描述
有一条直线,上有n个点,编号从0到n-1。当小A站在s点处,每次可以往前跳到s+1,也可以往前跳到s-1(当s-1 >= 0时),也可以调到2*s处。现在问小A最少跳多少次才能跳到点e处。
输入
多组输入。每组输入两个整数s,e(0 <= s,e <= 100,000)。n趋于无穷大。
输出
输出小A从s跳到e的最小次数。
示例输入
5 17
示例输出
4
提示
#include <stdio.h>
#include <math.h>
#include <string.h>
struct m
{
int x;
int num;
} d[4100000];
bool tf[4100000];
int bfs (int a,int b)
{
m now,next;
now.x = a;
now.num = 0;
int s = 0,e = 0;
d[s++] = now;
tf[now.x] = 1;
while (s > e)
{
now = d[e++];
//printf ("s = %d\tnum = %d\n",now.x,now.num);
if (now.x == b)
return now.num;
next.x = now.x - 1;
if (next.x >= 0 && next.x < 3000010 && tf[next.x] == 0)
{
next.num = now.num + 1;
d[s++] = next;
tf[next.x] = 1;
}
next.x = now.x + 1;
if (next.x >= 0 && next.x < 3000010 && tf[next.x] == 0)
{
next.num = now.num + 1;
d[s++] = next;
tf[next.x] = 1;
}
next.x = now.x * 2;
if (next.x >= 0 && next.x < 3000010 && tf[next.x] == 0)
{
next.num = now.num + 1;
d[s++] = next;
tf[next.x] = 1;
}
}
}
int main()
{
int s,e,i,k;
while (~scanf ("%d%d",&s,&e))
{
memset(tf,0,sizeof(tf));
int num = bfs(s,e);
printf ("%d\n",num);
}
return 0;
}
不要访问重复元素,会RE