POJ 3278 Catch That Cow —————— BFS

浅浅的花香味﹌ 2022-05-13 02:24 299阅读 0赞

Language:Default

Catch That Cow














Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 120100 Accepted: 37481

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

  1. 5 17

Sample Output

  1. 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.

Source

USACO 2007 Open Silver

—-

  1. /*
  2. 2018/9/9
  3. BFS
  4. x 有三个搜索方向
  5. x+1;
  6. x-1;
  7. x*2;
  8. 优先队列,找最短时间
  9. */
  10. #include<cstdio>
  11. #include<cstring>
  12. #include<algorithm>
  13. #include<iostream>
  14. #include<queue>
  15. using namespace std;
  16. const int MAXN=1e6+9;
  17. int n,k;
  18. bool vis[MAXN];
  19. struct node{
  20. int x,step;
  21. node(){};
  22. node(int _x,int _step)
  23. {
  24. x=_x; step=_step;
  25. }
  26. bool operator < (const node &b)const
  27. {
  28. return step==b.step?x<b.x:step>b.step;
  29. }
  30. };
  31. int bfs(int x)
  32. {
  33. memset(vis,0,sizeof(vis));
  34. vis[x]=1;
  35. node e1,e2;
  36. priority_queue<node> que;
  37. que.push(node(x,0));
  38. int ans=0;
  39. while(que.size())
  40. {
  41. e1=que.top();que.pop();
  42. if(e1.x==k)
  43. {
  44. ans=e1.step;
  45. break;
  46. }
  47. if(!vis[e1.x+1])
  48. {
  49. vis[e1.x+1]=1;
  50. que.push(node(e1.x+1,e1.step+1));
  51. }
  52. if(e1.x>0 && !vis[e1.x-1])
  53. {
  54. vis[e1.x-1]=1;
  55. que.push(node(e1.x-1,e1.step+1));
  56. }
  57. if(e1.x<=200000 && !vis[e1.x*2])
  58. {
  59. vis[2*e1.x]=1;
  60. que.push(node(e1.x*2,e1.step+1));
  61. }
  62. }
  63. return ans;
  64. }
  65. int main()
  66. {
  67. while(~scanf("%d %d",&n,&k))
  68. printf("%d\n",bfs(n));
  69. return 0;
  70. }

发表评论

表情:
评论列表 (有 0 条评论,299人围观)

还没有评论,来说两句吧...

相关阅读