[关闭]
@xunuo 2017-04-16T09:38:30.000000Z 字数 1705 阅读 963

Catch That Cow


Time Limit: 2000MS      Memory Limit: 65536K

BFS


Description

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?

Input

Line 1: Two space-separated integers: N and K
Output

Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.

Sample Input

5 17

Sample Output

4

Hint

The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes.

题意:

有一个牧羊人和一头牛,人在x点,牛在y点,他们都在一条数轴上,牧羊人想要去抓牛,但是他一次只能走到x+1,x-1或者是2*x处;在抓牛的过程中牛不动,问你牧羊人最短要多长时间能够抓到牛,人跳一次花一分钟;

解题思路:

把每种情况都走一遍,谁最先到达谁就是最短的,走过了的就标记一下;

完整代码:

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<queue>
  4. using namespace std;
  5. const int maxn=200000;////要开打两倍!!!估计是因为有2*x吧??!!。。
  6. int vis[200010];
  7. int ans;
  8. struct node
  9. {
  10. int x;
  11. int num;
  12. };
  13. int bfs(int st,int en)
  14. {
  15. queue<node>q;
  16. node now,next;
  17. now.x=st;
  18. now.num=0;
  19. vis[st]=1;
  20. q.push(now);
  21. while(!q.empty())
  22. {
  23. now=q.front();
  24. q.pop();
  25. if(now.x==en)
  26. {
  27. ans=now.num;
  28. break;
  29. }
  30. next=now;
  31. next.x=now.x+1;
  32. if(next.x>=0&&next.x<maxn&&vis[next.x]==0)
  33. {
  34. next.num=now.num+1;
  35. vis[next.x]=1;
  36. q.push(next);
  37. }
  38. next.x=now.x-1;
  39. if(next.x>=0&&next.x<maxn&&vis[next.x]==0)
  40. {
  41. next.num=now.num+1;
  42. vis[next.x]=1;
  43. q.push(next);
  44. }
  45. next.x=2*now.x;
  46. if(next.x>=0&&next.x<maxn&&vis[next.x]==0)
  47. {
  48. next.num=now.num+1;
  49. vis[next.x]=1;
  50. q.push(next);
  51. }
  52. }
  53. return ans;
  54. }
  55. int main()
  56. {
  57. int st,en;
  58. while(scanf("%d%d",&st,&en)!=EOF)
  59. {
  60. memset(vis,0,sizeof(vis));
  61. printf("%d\n", bfs(st,en));
  62. }
  63. return 0;
  64. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注