poj3278Catch That Cow

Posted いとう かいじ

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj3278Catch 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();
}

 

 

以上是关于poj3278Catch That Cow的主要内容,如果未能解决你的问题,请参考以下文章

POJ 3278 Catch That Cow

POJ 3278 Catch That Cow

POJ3278_Catch that cow

poj3278Catch That Cow

POJ 3278: Catch That Cow

poj3278 Catch That Cow