zoukankan      html  css  js  c++  java
  • 【poj3278】Catch That Cow

    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 - 1 or + 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

     
    题解
     
    题意:给定两个整数n和k,通过 n+1或n-1 或n*2 这3种操作,使得n==k,输出最少的操作次数
     
    bfs,找到的第一组就是最小步数
     
    #include<iostream>
    #include<cstdlib>
    #include<queue>
    #define N 1000000
    using namespace std;
    struct node
    {
        int x,step;
    };
    queue <node> Q;
    node first,now;
    bool vis[N+10];
    int n,k,ans;
    int check(int x)
    {
        if (x<0 || x>N ||vis[x]) return 0;
        return 1;
    }
    void extend(node in)
    {
        node p = in;
        p.step ++;
        p.x = in.x*2;
        if (check(p.x)) vis[p.x] = true,Q.push(p);
        p.x = in.x+1;
        if (check(p.x)) vis[p.x] = true,Q.push(p);
        p.x = in.x-1;
        if (check(p.x)) vis[p.x] = true,Q.push(p);
    }
    int bfs()
    {
        Q.push(first);
        while (!Q.empty())
        {
            now = Q.front();
            Q.pop();
            if (now.x == k) return now.step;
            extend(now);
        }
    }
    int main()
    {
        cin>>n>>k;
        first.x = n;
        cout<<bfs();
    }
     
  • 相关阅读:
    浅谈自动化测试
    Linux cron定时介绍
    Python上下文管理器
    Robot Framework robot命令
    Web自动化测试之playwright:设置浏览器语言
    Python文件及目录处理方法
    2021google开发者大会
    linux环境变量设置小结
    Eclipse快捷键
    java计时 小计
  • 原文地址:https://www.cnblogs.com/liumengyue/p/5576037.html
Copyright © 2011-2022 走看看