POJ训练计划3278_Catch That Cow/SDUT2782_我跳我跳我跳跳跳(一维BFS)

描述了一种在有限步数内捕获逃逸牛的方法,通过行走和瞬移两种方式在数轴上寻找目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Catch That Cow
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 43401 Accepted: 13512

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.

我跳我跳我跳跳跳

Time Limit: 1000MS Memory limit: 65536K

题目描述

有一条直线,上有n个点,编号从0到n-1。当小A站在s点处,每次可以往前跳到s+1,也可以往前跳到s-1(当s-1 >= 0时),也可以调到2*s处。现在问小A最少跳多少次才能跳到点e处。

输入

多组输入。每组输入两个整数s,e(0 <= s,e <= 100,000)。n趋于无穷大。

输出

输出小A从s跳到e的最小次数。

示例输入

5 17

示例输出

4

提示

 

来源


解题报告
比赛的时候根本没有想到是bfs解题的,还以为是背包呢,bfs一维。。。
多组输入每次都是忘了数组清零的节奏。。。
#include <iostream>
#include <stdio.h>
#include <string.h>


using namespace std;
struct node
{
    int x,num;
}q[1000000];
int s,e;
int v[1000000];
void bfs()
{
    node now,next;
    int t=0,f=0;
    now.x=s;
    now.num=0;
    q[f++]=now;
    v[now.x]=1;
    while(t<f)
    {

        now=q[t++];
        //printf("x =%d,num =%d\n",now.x,now.num);
        if(now.x==e)
        {
            printf("%d\n",now.num);
            return ;
        }
        next.x=now.x+1;
        if(next.x>=0&&next.x<300000&&v[next.x]!=1 )
        {
            next.num=now.num+1;
            q[f++]=next;
            v[next.x]=1;
        }
        next.x=now.x-1;
        if(next.x>=0&&next.x<300000&&v[next.x]!=1)
        {
            next.num=now.num+1;
            q[f++]=next;
            v[next.x]=1;
        }
        next.x=now.x*2;
        if(next.x>=0&&next.x<300000&&v[next.x]!=1)
        {
            next.num=now.num+1;
            q[f++]=next;
            v[next.x]=1;
        }
    }
}
int main(){
    while(~scanf("%d%d",&s,&e)){
        memset(v,0,sizeof(v));
        bfs();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值