POJ3278--Catch That Cow(BFS)

题目来源:poj 3278

题意:
FJ要抓奶牛。
开始输入N(FJ的位置)K(奶牛的位置)。
FJ有三种移动方法:
1、向前走一步,耗时一分钟。
2、向后走一步,耗时一分钟。
3、向前移动到当前位置的两倍N*2,耗时一分钟。
问FJ抓到奶牛的最少时间。PS:奶牛是不会动的。

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.

思路:最普通的DFS。唯一需要注意的一点是要判断N和K的关系,若N>=K,那么不需要进入BFS进行搜索了,直接输出N-K即可。否则会报错。

#include <iostream>
#include <queue>
#include <map>
using namespace std;
struct node
{
    int x;
    int step;
};
queue<node> Q;
map<int, bool> M;
const int maxn = 100001;
void bfs(int n, int k)
{
    node temp;
    temp.x = n;
    temp.step = 0;
    Q.push(temp);
    while (!Q.empty())
    {
        node top = Q.front();
        Q.pop();
        for (int i = 0; i < 3; i++)
        {
            node temp = top;
            if (i == 0)
            {
                temp.x = top.x - 1;
            }
            else if (i == 1)
            {
                temp.x = top.x + 1;
            }
            else
            {
                temp.x = 2 * top.x;
            }
            if (temp.x < 0 || temp.x > maxn || M[temp.x])
            {
                continue;
            }
            temp.step = top.step + 1;
            M[temp.x] = true;
            if (temp.x == k)
            {
                cout << temp.step << endl;
                return;
            }
            Q.push(temp);
        }
    }
}
int main()
{
    int n, k;
    cin >> n >> k;
    if (n >= k)
    {
        cout << n - k;
    }
    else
    {
        bfs(n, k);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39504764/article/details/89875051
今日推荐