POJ3278 Catch That Cow

Catch That Cow
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 68975   Accepted: 21699

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.

題意:初始點在N,目標點在K,但是每分鐘只能向前或後退一步,或者到達這個點的2倍的點。最快要多久能從N點到達K點。

思路:  每次有三種情況,隨意就是用了BFS,剛寫成的時候,沒有優化,導致超內存,後來修改,如果當前點超過了目標點K,就不再向前走,如果當前點小於0,就不能在後退,之後又TLE,然後發現沒有優化那些走過的點,再次修改,終於AC了

代碼如下:

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#define MXAN 1000005
using namespace std;

struct Node
{
    int add,step;//add代表當前地址,step代表步數
};

int N,K;
bool ok[MXAN];  //標記這點是否到達過
queue<Node> Q;

int bfs()
{
    int r,c;
    Node tem={N,0};
    Q.push(tem);
    while(!Q.empty())
    {
        tem=Q.front();
        if(tem.add==K) break;
        Q.pop();
        if(!ok[tem.add])   //如果這點遍歷過,就不能在遍歷
        {
            if(tem.add<K ) //如果這點小於目標點,可以繼續+1或*2
            {
                r=tem.add+1;
                Node temp={r,tem.step+1};
                Q.push(temp);

                c=tem.add*2;
                Node tep={c,tem.step+1};
                Q.push(tep);
            }
            if(tem.add>0 && !ok[tem.add])  //如果這點大於0,就能向後走
            {
                r=tem.add-1;
                Node tp={r,tem.step+1};
                Q.push(tp);
            }
            ok[tem.add]=true;  //把這點標記爲已經遍歷過
        }
    }
    while(!Q.empty())
    {
        Q.pop();
    }

    return tem.step;
}

int main()
{
    memset(ok,0,sizeof(ok));
    scanf("%d%d",&N,&K);
    int ans=bfs();
    printf("%d\n",ans);
    return 0;
}

發佈了50 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章