• PoJ3278--Catch That Cow(Bfs)


    Catch That Cow

    Time Limit: 2000MS   Memory Limit: 65536K
    Total Submissions: 61317   Accepted: 19155

    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.

    Source

     
     
    RE: 坐标轴上有两个点(a、b), 求 a 接近 b 所需走的最小步数;
      有三种走法,(x-1)、 (x+1)、(2*x);
      a > b  → → 输出;
      else :: Bfs;
      
     1 #include <queue>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <iostream>
     5 using namespace std;
     6 
     7 const int maxn = 100000 + 5;
     8 int vis[maxn], cnt[maxn];
     9 queue <int> q;
    10 
    11 void Bfs()
    12 {
    13     int nx;
    14     while(!q.empty())
    15     {
    16         int x = q.front();  q.pop();
    17         for(int i = 0; i < 3; i++)    //三种走法; 
    18         {
    19             if(i == 0) nx = x + 1;
    20             else if(i == 1) nx = x - 1;
    21             else nx = 2 * x;
    22             if(nx >= 0 && nx <= 100000 && !vis[nx])  //遍历到最后找最优?::剪枝? 
    23             {
    24                 vis[nx] = 1;
    25                 cnt[nx] = cnt[x] + 1;
    26                 q.push(nx);     
    27             } 
    28         }     
    29     }
    30 }
    31 
    32 int main()
    33 {
    34     int m, n;
    35     while(~scanf("%d %d", &m, &n))
    36     {
    37         if(m > n)
    38         {
    39             printf("%d
    ", m - n);
    40             return 0;
    41         }
    42         memset(vis, 0, sizeof(vis));
    43         vis[m] = 1;
    44         cnt[m] = 0;
    45         q.push(m);
    46         Bfs();
    47         printf("%d
    ", cnt[n]);
    48     } 
    49     return 0;
    50 }
     
      
  • 相关阅读:
    no match for call to ‘(std::__cxx11::string {aka std::__cxx11::basic_string
    一转眼,已四年
    线程或进程绑定到特定的cpu
    微信好友信息统计-图、词云和热图
    微信聊天机器人-存储好友分享消息
    Qt之加减乘除四则运算-支持负数
    windows粘贴板操作-自己的应用和windows右键互动
    Qt之QDomDocument操作xml文件-模拟ini文件存储
    Qt之表格控件蚂蚁线
    Qt之移动硬盘热插拔监控
  • 原文地址:https://www.cnblogs.com/soTired/p/4708873.html
Copyright © 2020-2023  润新知