• POJ - 3278 Catch That Cow


    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

    InputcopyOutputcopy
    5 17
    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.

    代码:

    1. #include<iostream>
    2. #include<queue>
    3. using namespace std;
    4. const int MAX=1e5+5;
    5. int dis[MAX];
    6. int main(){
    7. int N,K;
    8. cin>>N>>K;
    9. queue<int>q;
    10. q.push(N);
    11. while(!q.empty()){
    12. int x=q.front();
    13. q.pop();
    14. if(x==K){
    15. cout<<dis[x]<<endl;
    16. break;
    17. }
    18. if(x-1>=0&&!dis[x-1]){
    19. q.push(x-1);
    20. dis[x-1]=dis[x]+1;
    21. }
    22. if(x+1<=MAX&&!dis[x+1]){
    23. q.push(x+1);
    24. dis[x+1]=dis[x]+1;
    25. }
    26. if((x<<1)<=MAX&&!dis[x<<1]){
    27. q.push(x<<1);
    28. dis[x<<1]=dis[x]+1;
    29. }
    30. }
    31. return 0;
    32. }

  • 相关阅读:
    Windows端口号被占用的查看方法及解决办法
    Ajax学习笔记第二天
    【无标题】
    Django学习过程01
    身边的那些信审人员都去哪了?
    day25--Java集合08
    这套软件测试笔试试卷、能拿满分的至少都是月薪30K的
    leetcode669. 修剪二叉搜索树(java)
    java“贪吃蛇”小游戏
    析构函数详解
  • 原文地址:https://blog.csdn.net/m0_56312312/article/details/125461894