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();
    }
     
  • 相关阅读:
    软件测试面试题及答案【史上最全】
    Loadrunner参数(摘)
    Linux系统的目录结构
    关于梦想(七)
    Mysql基于Linux上的安装
    走进MySQL
    关于梦想(六)
    Jmeter的实例应用
    十种社会中最真实的人际关系
    有些人走了就走了,该在的还在就好
  • 原文地址:https://www.cnblogs.com/liumengyue/p/5576037.html
Copyright © 2011-2022 走看看