暑假集训第三周 STL J - Catch That Cow 抓捕奶牛

32 篇文章 0 订阅
这是一篇关于如何运用STL和深度搜索(深搜)策略来解决一个数学问题的文章。农夫John需要在数轴上追赶位于点K的逃牛,他可以从点N出发,通过步行或瞬移两种方式移动。步行可在1分钟内移动到当前位置的相邻点,瞬移可将他带到当前位置的两倍。题目要求计算在牛不移动的情况下,John抓到牛所需的时间。这是一个适合用广度优先搜索(BFS)和队列来解决的问题。
摘要由CSDN通过智能技术生成


J - Catch That Cow
Time Limit:2000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

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.
分析:

这是一个广搜+队列的问题,很复杂的问题用这些方法就能很轻松的写出来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<iostream>
#include<queue>
#include<stdio.h>
#include<string.h>
using namespace std;
queue<int> q;
int step[100001],visit[100001];
int  main()
{
    int a,b;
    while(scanf("%d %d",&a,&b)!=EOF)
    {
        memset(visit,0,sizeof(visit));
        if(a>=b)
            printf("%d\n",a-b);
        else
        {
            int t,temp;
            queue<int>q;
            q.push(a);  // 插入队列
            visit[a]=1;
            while(!q.empty())
            {
                t=q.front();//队列首元素
                q.pop();   //出队列
                for(int i=0; i<3; i++)
                {
                    if(i==0)
                        temp=t+1;
                    else if(i==1)
                        temp=t-1;
                    else
                        temp=t*2;

                    if(temp>100000||temp<0)
                        continue;
                    if(visit[temp]==0)
                    {
                        step[temp]=step[t]+1;
                        if(temp==b)
                            printf("%d\n",step[temp]);
                        visit[temp]=1;
                        q.push(temp);

                    }
                }
            }
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值