题意:John的奶牛丢失了,现在有人告诉他奶牛的位置为e, 而他自己的位置为s,e与s在同一条直线上。现在John去追赶他的奶牛,他又两种方式可以选择。
1. 在任意位置 x 可以走到 x-1 或者 x + 1, 耗时一分钟
2. 在任意位置 x 可以走到 x * 2, 耗时一分钟。
求出John追上奶牛所需的最少时间。
题解:说明一下。一开始我将数组开到200000,用来计算跳出100000之后又返回的情况。其实这完全没有必要。因为如果某一路径途中大于100000,那么一定存在另一条路径不会经过大于100000的点,且后一路径所花时间小于等于前一路径。举个简单的例子。从60000-120000-100000 > 60000-50000-100000
#include <queue>
#include <iostream>
using namespace std;
int s, e;
int step[100001], check[100001];
int bfs ()
{
queue<int> Q;
Q.push ( s );
step[s] = 0;
check[s] = 1;
int cur, next;
while ( ! Q.empty () )
{
cur = Q.front ();
Q.pop();
if ( cur == e )
return step[cur];
next = cur - 1;
if ( next >= 0 && next < 100001 && ! check[next] )
{
check[next] = 1;
step[next] = step[cur] + 1;
Q.push ( next );
}
next = cur + 1;
if ( next >= 0 && next < 100001 && ! check[next] )
{
check[next] = 1;
step[next] = step[cur] + 1;
Q.push ( next );
}
next = cur * 2;
if ( next >= 0 && next < 100001 && !check[next] )
{
check[next] = 1;
step[next] = step[cur] + 1;
Q.push ( next );
}
}
return 0;
}
int main()
{
while ( scanf("%d%d",&s,&e) != EOF )
{
memset(check,0,sizeof(check));
printf("%d\n", bfs());
}
return 0;
}