POJ-3278-Catch That Cow

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

Status

Practice

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

题意:给出起点,终点坐标,注意坐标都只在一条数轴上。对起点有三种操作,向前一位,向后一位,起点乘以2.每种操作都消耗一个单位时间,求出到达终点最短时间.

广度优先搜索。
昨天做了二维的,上午做了三维的,现在又来了一维的。。。。

代码

#include<stdio.h>
#include<string.h>
#include<string>
#include<stack>
#include<queue>
#include<math.h>
#include<limits.h>
#include<iostream>
#include<algorithm>
#define SIZE 100001
using namespace std;
queue<int>q;
bool visited[SIZE];//已访问的坐标标记为true
int step[SIZE];//记录坐标对应的步数
int bfs(int n, int k)//广度优先搜索
{
    int head,next;
    q.push(n);
    visited[n]=true;
    step[n]=0;
    while(!q.empty())//优先队列
    {
        head=q.front();
        q.pop();
        for(int i=0; i<3; i++)//三个搜索的方向
        {
            if(i==0)
                next=head-1;//向后
            else if (i == 1)
                next=head+1;//向前
            else
                next=head*2;//传送
            if(next>SIZE||next<0||visited[next])//坐标不合法或者坐标已被访问过
                continue;
            if(!visited[next])
            {
                q.push(next);
                step[next]=step[head]+1;//步数加一
                visited[next]=true;//标记为已访问
            }
            if(next==k)
                return step[next];//到达终点
        }
    }
}
int main()
{
    int n,k;
    cin>>n>>k;
    if(n>=k)//可能起点在终点后面,那只能一步一步退回去
        cout<<n-k<<endl;
    else
        cout<<bfs(n,k)<<endl;
    return 0;
}

你可能感兴趣的:(搜索,bfs)