CUC-SUMMER-2-E

E - Catch That Cow
POJ - 3278

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.


題意:JOHN要抓住他的牛,有兩種移動方式,坐標加一或減一,坐標翻倍,牛不會動,求最少移動幾次。

解法:寬搜,遞歸,開一個和范圍一樣大的數(shù)組來記錄坐標是否到達過,從起始點進行三種移動,將移動后坐標標記并加到隊列中,如果移動后坐標已經(jīng)被標記了則返回,這說明一定可以用更少的移動到達這一點。

代碼:

#include<iostream>
#include<queue>
using namespace std;
int ans=0;
int a[100100]={0,};
int n,k;
struct point{
    int x,step;
};
queue <point> q;
point start;
int BFS()
{
    while(!q.empty()){
        point now;
        now=q.front();
        q.pop();
        if(now.x==k){
            n=k;
            ans=now.step;
            return ans;
        }
        for(int i=0;i<3;i++){
            point next;
            if(i==0)
                next.x=now.x+1;
            else if(i==1)
                next.x=now.x-1;
            else
                next.x=now.x*2;
            next.step=now.step+1;
            if(next.x>=0&&next.x<100100&&a[next.x]==0){
                a[next.x]=1;
                q.push(next);
            }
        }
    }
    return ans;
}
int main()
{
    cin>>n>>k;
    start.x=n;
    start.step=0;
    q.push(start);
    a[n]=1;
    cout<<BFS()<<endl;
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容