首页 > 其他 > 详细

POJ 3278 - Catch That Cow - [BFS]

时间:2018-09-20 00:19:07      阅读:192      评论:0      收藏:0      [点我收藏+]

题目链接:http://poj.org/problem?id=3278

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

 

题意:

有一条数字线段 $[0,100000]$,已知农场主在位置 $N$,逃亡的奶牛在位置 $K$ 不移动,现在农场主在每一分钟都可以有三种行进方式:

往右走一步,往左走一步,传送到为当前位置的两倍的地方;

求最短多少分钟可以抓到奶牛。

 

题解:

显然是BFS,农场主每行进一次,相当于BFS往下搜一层,那么所有BFS搜索到的位置的深度就相当于行进时间(并且就是到达这个位置的最短时间),

如果某一层遇到了奶牛,就直接终止BFS即可。

时间复杂度:所有的点只会进队一次,$O(N)$。

 

AC代码:

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;

const int maxn=100000;

int n,k;
int d[maxn+10];
bool vis[maxn+10];

inline bool ok(int x)
{
    if(0<=x && x<=maxn) return 1;
    else return 0;
}
void bfs()
{
    queue<int> q;
    q.push(n);
    d[n]=0;
    vis[n]=1;
    while(!q.empty())
    {
        int now=q.front(); q.pop();
        if(now==k) return;
        int x1=now+1,x2=now-1,x3=2*now;
        if(ok(x1) && !vis[x1]) q.push(x1),d[x1]=d[now]+1,vis[x1]=1;
        if(ok(x2) && !vis[x2]) q.push(x2),d[x2]=d[now]+1,vis[x2]=1;
        if(ok(x3) && !vis[x3]) q.push(x3),d[x3]=d[now]+1,vis[x3]=1;
    }
}

int main()
{
    cin>>n>>k;
    memset(vis,0,sizeof(vis));
    bfs();
    cout<<d[k]<<endl;
}

 

POJ 3278 - Catch That Cow - [BFS]

原文:https://www.cnblogs.com/dilthey/p/9678263.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!