总时间限制: 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.

样例输入

  1. 5 17

样例输出

  1. 4

思路

这是一个求最少步数的问题, 特别适合用广度优先搜索解决.

改进后完整代码如下:

  1. #include <iostream>
  2. #include <cstring>
  3. #include <queue>
  4. using namespace std;
  5. int N, K;
  6. const int MAXN = 100000; // 要开很大的数组才行
  7. int visited[MAXN + 10]; // 判重标记, visited[i] = true表示i已扩展
  8. typedef struct Step {
  9. int x; // 位置
  10. int steps; // 到达x所需的步数
  11. Step(int xx, int s): x(xx), steps(s) {}
  12. }Step;
  13. queue<Step> OpenQueue; // Open队列
  14. int main() {
  15. /* Read data and initialize them */
  16. cin >> N >> K;
  17. memset(visited, 0x0, sizeof(visited));
  18. OpenQueue.push(Step(N, 0));
  19. visited[N] = 1;
  20. /* BFS */
  21. while( !OpenQueue.empty() ) {
  22. Step s = OpenQueue.front();
  23. if( s.x == K ) { // 找到目标
  24. cout << s.steps << endl;
  25. return 0;
  26. } else {
  27. if( s.x - 1 >= 0 && !visited[s.x-1] ) { // 左走一步
  28. OpenQueue.push(Step(s.x-1, s.steps+1));
  29. visited[s.x-1] = 1;
  30. }
  31. if( s.x + 1 <= MAXN && !visited[s.x+1] ) { // 右走一步
  32. OpenQueue.push(Step(s.x+1, s.steps+1));
  33. visited[s.x+1] = 1;
  34. }
  35. if( s.x*2 <= MAXN && !visited[2 * s.x] ) { // 横跳
  36. OpenQueue.push(Step(2 * s.x, s.steps+1));
  37. visited[2 * s.x] = 1;
  38. }
  39. OpenQueue.pop();
  40. }
  41. }
  42. return 0;
  43. }