kuangbin 专题一 简单搜索 (POJ 3278) Catch The Cow

博客围绕Catch The Cow问题展开,农夫约翰要在数轴上抓住牛,有步行和传送两种移动方式。作者起初用暴力法超时,后采用BFS和队列解决该问题,还提到POJ不支持万能头文件。

Catch The Cow

Time limit2000 ms
Memory limit65536 kB
OSLinux

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.

农夫约翰已被告知逃亡牛的位置,并希望立即抓住它。他开始于一个点N(0≤ N ≤100,000)上的某条线,牛是在点K(0≤ K≤100,000)与点N在同一条线上。农夫约翰有两种交通方式:步行和传送。

  • 行走:农夫约翰可以在一分钟内从任意点X移动到X -1或X + 1 点
  • 传送:农夫约翰可以在一分钟内从任意点X移动到2× X点

如果母牛不知道农夫约翰在追它,根本不动,那么农夫约翰需要多长时间才能找回它?

  • 输入`
第1行:两个以空格分隔的整数:N和K.
  • 输出
第1行:Farmer John捕捉逃亡牛所需的最短时间(以分钟为单位)。
  • 样例输入
5 17
  • 样例输出
4
  • 提示
农夫约翰到达逃亡牛的最快方法是沿着以下路径前进:5-10-9-18-17,这需要4分钟。

我一开始用暴力显然超时le
用BFS和队列写
然后输入有很多组…我被它的第一行蒙蔽了双眼
说起来POJ不支持万能头文件好气哦
这里是一个为了STL库写了半像不像C++的菜鸡_(:з」∠)_

ime188ms
Memory1216kB
Length919
LangC++
#include<iostream>
#include <cstdio>
#include <queue>
#include <cstring>
int f[100005];/*记录是否到过该位置*/
using namespace std;
int bfs(int x,int y){
    int num, mins;
    queue<int>q;
    q.push(x);
    q.push(0);/*压入位置点和时间*/
    while(!q.empty()) {
      num = q.front();
      q.pop();
      mins = q.front();
      q.pop();
      if(num == y) return mins;
      else {
        if(num - 1 >= 0 && !f[num - 1]) {
          f[num - 1] = 1;
          q.push(num - 1);
          q.push(mins + 1);
        }
        if(num * 2 <= 100005 && !f[num * 2]) {
          f[num * 2] = 1;
          q.push(num * 2);
          q.push(mins + 1);
        }
        if(num + 1 <= y && !f[num + 1]) {
          f[num + 1] = 1;
          q.push(num + 1);
          q.push(mins + 1);
        }
      }
    }
  }
  int main() {
    int n, k;
    while(~scanf("%d %d", &n, &k)) {
      memset(f, 0, sizeof(f));
      cout << bfs(n, k) << endl;
    }
    return 0;
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值