zoukankan      html  css  js  c++  java
  • 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 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.
     1 #include <iostream>
     2 #include <queue>
     3 using namespace std;
     4 
     5 struct node{
     6     int loc, step;//loc 当前位置, step 次数
     7 }pos,q;
     8 
     9 queue<node> que;
    10 int vis[200005];
    11 
    12 void Push(int loc, int step){
    13     q.loc = loc;
    14     q.step = step + 1;
    15     vis[loc] = 1;
    16     que.push(q);
    17 }
    18 
    19 int bfs(int n, int k){
    20     pos.loc = n, pos.step = 0;
    21     vis[n] = 1;
    22     que.push(pos);
    23     while(!que.empty()){
    24         pos = que.front();
    25         que.pop();
    26         if(pos.loc == k)
    27             return pos.step;
    28         int loc_mov = pos.loc - 1;
    29         if(loc_mov >= 0 && loc_mov < 200005 && vis[loc_mov] == 0){
    30             Push(loc_mov, pos.step);
    31         }
    32         loc_mov = pos.loc + 1;
    33         if(loc_mov >= 0 && loc_mov < 200005 && vis[loc_mov] == 0){
    34             Push(loc_mov, pos.step);
    35         }
    36         loc_mov = 2 * pos.loc;
    37         if(loc_mov >= 0 && loc_mov < 200005 && vis[loc_mov] == 0){
    38             Push(loc_mov, pos.step);
    39         }
    40     }
    41     return -1;
    42 }
    43 
    44 int main(){
    45     int n, k;
    46     cin >> n >> k;
    47     cout << bfs(n, k) << endl;
    48 }
  • 相关阅读:
    php高级进阶系列文章--第二篇(PHP基础知识复习)
    开发常用linux命令
    composer 包管理工具学习总结
    微信菜单加emoji图标
    onethink导出excel
    onethinkp导入excel
    导航效果css
    php发送邮件
    js初学者的div移动
    html图片预览
  • 原文地址:https://www.cnblogs.com/jxust-jiege666/p/6683806.html
Copyright © 2011-2022 走看看