总时间限制: 2000ms 内存限制: 65536kB
描述
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
- Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
- Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
输入
Line 1: Two space-separated integers: N and K
输出
Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
样例输入
5 17
样例输出
4
思路
这是一个求最少步数的问题, 特别适合用广度优先搜索解决.
改进后完整代码如下:
#include <iostream>#include <cstring>#include <queue>using namespace std;int N, K;const int MAXN = 100000; // 要开很大的数组才行int visited[MAXN + 10]; // 判重标记, visited[i] = true表示i已扩展typedef struct Step {int x; // 位置int steps; // 到达x所需的步数Step(int xx, int s): x(xx), steps(s) {}}Step;queue<Step> OpenQueue; // Open队列int main() {/* Read data and initialize them */cin >> N >> K;memset(visited, 0x0, sizeof(visited));OpenQueue.push(Step(N, 0));visited[N] = 1;/* BFS */while( !OpenQueue.empty() ) {Step s = OpenQueue.front();if( s.x == K ) { // 找到目标cout << s.steps << endl;return 0;} else {if( s.x - 1 >= 0 && !visited[s.x-1] ) { // 左走一步OpenQueue.push(Step(s.x-1, s.steps+1));visited[s.x-1] = 1;}if( s.x + 1 <= MAXN && !visited[s.x+1] ) { // 右走一步OpenQueue.push(Step(s.x+1, s.steps+1));visited[s.x+1] = 1;}if( s.x*2 <= MAXN && !visited[2 * s.x] ) { // 横跳OpenQueue.push(Step(2 * s.x, s.steps+1));visited[2 * s.x] = 1;}OpenQueue.pop();}}return 0;}
