kuangbin专题一 简单搜索 抓住那头牛(POJ-3278)

Catch That Cow

Time Limit: 2000MS Memory Limit: 65536K

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 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 和终点 K , 假设当前位置为 X , 有三种移动方式,第一种是往左走一个单位长度,即变成 X - 1 ; 第二种是往右走一个单位长度,即变成 X + 1 ; 第三种是从 X 变成 2 * X 。 每种移动方式消耗的时间都是一分钟。求得从起始点到终点的最短耗费时间。



解题思路

这道题很简单,就是在一个X轴上的BFS求最短路模型,只要按照思路写就行。

/*   一切都是命运石之门的选择  El Psy Kongroo  */
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<cmath>
#include<functional>
using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef pair<int, pii> piii;
typedef pair<double, double> pdd;
typedef pair<string, pii> psi;
typedef __int128 int128;
#define x first
#define y second
const int inf = 0x3f3f3f3f, mod = 1e9 + 7;

const int N = 1e5 + 10;
int sx, tx;    //起点 终点
int dist[N];

//判断位置是否合法
bool check(int x){
    return x >= 0 && x < N && dist[x] == -1;  
}

int bfs(){
    memset(dist, -1, sizeof(dist));
    queue<int> q;  q.push(sx);
    dist[sx] = 0;

    while(!q.empty()){
        int x = q.front();
        q.pop();

        if(x == tx) return dist[x];   //到达终点

        if(check(x - 1)) q.push(x - 1), dist[x - 1] = dist[x] + 1;
        if(check(x + 1)) q.push(x + 1), dist[x + 1] = dist[x] + 1;
        if(check(2 * x)) q.push(2 * x), dist[2 * x] = dist[x] + 1;
    }

    return -1;
}

int main(){
    cin >> sx >> tx;
    int res = bfs();

    cout << res << endl;

    return 0;
}
posted @ 2023-04-14 20:23  MarisaMagic  阅读(18)  评论(0编辑  收藏  举报