♥POJ 3278-Catch That Cow【搜索】

淩亂°似流年 2022-08-20 13:28 235阅读 0赞

C - Catch That Cow

Crawling in process… Crawling failed

Time Limit: 2000MS Memory Limit: 65536KB 64bit IO Format: %I64d & %I64u

Submit Status Practice POJ 3278

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.

解题思路:

题目大意就是有一个农夫和一头牛,在n,k,农夫想要到牛哪里,有两种移动方式,第一是坐标加1,第二是坐标乘2。注意搜索时超内存。

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<queue>
  4. #include<algorithm>
  5. using namespace std;
  6. struct node
  7. {
  8. int x,step;
  9. };
  10. int flag[100005];
  11. bool judge(node p)
  12. {
  13. if(p.x<0||p.x>100000||p.step>flag[p.x])//判断到这一点时间是不是最短的 是否更新
  14. return false;
  15. return true;
  16. }
  17. int main()
  18. {
  19. int n,k;
  20. while(scanf("%d%d",&n,&k)!=EOF)
  21. {
  22. if(n==k)
  23. {
  24. printf("0\n");
  25. continue;
  26. }
  27. memset(flag,0x7f,sizeof(flag));
  28. node ks;
  29. ks.x=n;
  30. ks.step=0;
  31. flag[ks.x]=0;
  32. queue<node>q;
  33. q.push(ks);
  34. int wc=0;
  35. while(!q.empty())
  36. {
  37. node end,end2;
  38. end2=q.front();
  39. q.pop();
  40. for(int i=0;i<3;i++)
  41. {
  42. end=end2;
  43. if(i==0)
  44. {
  45. end.x++;
  46. }
  47. if(i==1)
  48. {
  49. end.x*=2;
  50. }
  51. if(i==2)
  52. {
  53. end.x--;
  54. }
  55. end.step=end2.step+1;
  56. if(!judge(end))//如果不判断一下 直接进队是会超内存 各种超内存
  57. {
  58. continue;
  59. }
  60. if(end.x==k)
  61. {
  62. printf("%d\n",end.step);
  63. wc=1;
  64. break;
  65. }
  66. flag[end.x]=end.step;
  67. q.push(end);
  68. }
  69. if(wc==1)
  70. break;
  71. }
  72. }
  73. return 0;
  74. }

发表评论

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

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

相关阅读