前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Catch That Cow (POJ - 3278)(简单BFS)

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

作者头像
Lokinli
发布2023-03-09 16:39:03
2090
发布2023-03-09 16:39:03
举报
文章被收录于专栏:以终为始以终为始

转载请注明出处: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("%d\n",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("%d\n",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.

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-09-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档