Catch That Cow (POJ - 3278)(简单BFS)

2023-03-09 16:39:03 浏览数 (2)

转载请注明出处:https://blog.csdn.net/Mercury_Lc/article/details/82693928   作者:Mercury_Lc

题目链接

题解:给你x、y,x可以加1、减1、或者变成2*x,问通过最少的次数来让x等于y,这是最基础的bfs,就是把x通过一次的 1、-1、*2得到的数都放到队列里面,再把这些通过一次操作得到的数进行相同的操作 1、-1、*2,因为用个结构体来存放这个数是第几次操作得到的,所以只要一旦发现这个数,一定是通过最小的次数得到的。

代码语言:javascript复制
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const int maxn = 1e6   10;
int vis[maxn];
struct node
{
    int data;
    int step;
} w,l;
void bfs(int n,int k)
{
    memset(vis,0,sizeof(vis));
    vis[n] = 1;
    queue<node>q;
    w.data = n;
    w.step = 0;
    q.push(w);
    while(!q.empty())
    {
        w = q.front();
        q.pop();
        if(w.data == k)
        {
            printf("%dn",w.step);
            return ;
        }
        if(w.data   1 <= maxn && !vis[w.data   1])
        {
            l = w;
            l.data  = 1;
            l.step   ;
            q.push(l);
            vis[l.data] = 1;
        }
        if(w.data - 1 <= maxn && w.data - 1 >= 0&& !vis[w.data - 1])
        {
            l = w;
            l.data -= 1;
            l.step  ;
            q.push(l);
            vis[l.data] = 1;
        }
        if(w.data * 2 <= maxn && !vis[w.data * 2])
        {
            l =w;
            l.step  ;
            l.data *= 2;
            q.push(l);
            vis[l.data] = 1;
        }
    }
    return ;
}
int main()
{
    int n,k;
    while(~scanf("%d %d",&n,&k))
    {
        if(n > k)
            printf("%dn",n - k);
        else
            bfs(n, k);
    }
    return 0;
}

Problem 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.

0 人点赞