zoukankan      html  css  js  c++  java
  • POJ 3278 Catch that cow(BFS)

    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.
    题解:
      BFS,注意剪枝。
    #include<iostream>
    #include<cstring>
    #include<queue>
    using namespace std;
    const int maxn=1e5+5;
    bool vis[maxn*2];
    struct node
    {
        int x,step;
    };
    int k;
    int bfs(int n)
    {
        queue<node> que;
        node now;
        now.x=n;
        now.step=0;
        que.push(now);
        while(que.size())
        {
            now=que.front();
            que.pop();
            node next;
            if(now.x==k)
                return now.step;
            if(now.x<k&&!vis[now.x+1])
            {
                next.x=now.x+1;
                vis[next.x]=true;
                next.step=now.step+1;
                que.push(next);
            }
            if(now.x>0&&!vis[now.x-1])
            {
                next.x=now.x-1;
                vis[next.x]=true;
                next.step=now.step+1;
                que.push(next);
            }
            if(now.x<k&&!vis[now.x*2])
            {
                next.x=now.x*2;
                vis[next.x]=true;
                next.step=now.step+1;
                que.push(next);
            }
        }
        return -1;
    }
    int main()
    {
        int n;
        while(cin>>n>>k)
        {
            memset(vis,false,sizeof(vis));
            cout<<bfs(n)<<endl;
        }
        return 0;
    }
  • 相关阅读:
    win7-64位,vs32位,odbc 连接oracle问题总结
    vscode 格式化代码
    vue 自动切换导航图
    Unexpected console statement
    css flex 布局之---骰子
    vue百度地图在IE11下空白
    css使用font-face
    centos7计划任务
    MySQL(Mariadb)主从同步基础
    Ubuntu(16.04) 常见问题
  • 原文地址:https://www.cnblogs.com/orion7/p/7306973.html
Copyright © 2011-2022 走看看