POJ - 3278:Catch That Cow(BFS + STL)

原题链接
农夫知道一头牛的位置,想要抓住它。农夫和牛都于数轴上 ,农夫起始位于点 N(0<=N<=100000) ,牛位于点 K(0<=K<=100000) 。农夫有两种移动方式: 1、从 X移动到 X-1或X+1 ,每次移动花费一分钟 2、从 X移动到 2*X ,每次移动花费一分钟 假设牛没有意识到农夫的行动,站在原地不。最少要花多少时间才能抓住牛?
Input
一行: 以空格分隔的两个字母: N 和 K
Output
一行: 农夫抓住牛需要的最少时间,单位分钟
Sample Input
5 17
Sample Output
4
Hint
农夫使用最短时间抓住牛的方案如下: 5-10-9-18-17, 需要4分钟.

题目描述

农夫有三种行走方式:1、后退1个单位;2、前进1个单位;3、前进当前位置的2倍;每走一次都花费1分钟,求农夫抓到牛的最短时间(牛不动)

思路:使用广搜,将每种情况都遍历,那么第一个满足条件的,必然就是用时最短的行走方式

代码如下

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <queue>
#include <string.h>

using namespace std;

int n,k;
int book[100005];

struct node
{
    int x,step;
};

int bfs()
{
    int i;
    queue<node> q;
    while(!q.empty())
        q.pop();
    node now, next;
    now.x = n;
    now.step = 0;
    book[now.x] = 1;
    q.push(now);
    while(!q.empty())
    {
        now = q.front();
        q.pop();
        for(i = 0;i < 3;i++)
        {
            if(i == 0)
                next.x = now.x - 1;
            else if(i == 1)
                next.x = now.x + 1;
            else if(i == 2)
                next.x = now.x * 2;
            next.step = now.step + 1;
            if(next.x == k)
                return next.step;
            if(next.x > 0 && next.x < 100001 && book[next.x] == 0)	//这块判断时先判断下标是否越界
            {
                q.push(next);
                book[next.x] = 1;
            }
        }
    }
}

int main()
{
    scanf("%d %d",&n,&k);
    memset(book, 0, sizeof(book));
    if(n >= k)
        printf("%d\n",n-k);
    else
        printf("%d\n",bfs());
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值