hdoj2717 Catch That Cow

题目:

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

题目的意思也不难:给你两个数,一个是起点,另一个是终点。
求出从起点到终点所用的最小操作次数。
有三种操作方式:
对当前数加1;对当前数-1;对当前数*2.

这道题可以用广搜的方法。

参考代码:

#include 
#include 
#include 
using namespace std;
const int N = 100000+10;

int dir[3] = {-1, 1, 2};//三个方向值,分别代表三种不同的操作;

struct node {
    int x;//当前结点的值;
    int step;//此时已经经过了多少步;
} que[N];//队列的思想;

int map[N];//已访问过的;

int bfs(int s, int t) {
    memset(map, 0, sizeof(map));
    memset(que, 0, sizeof(que));
    int l = 0, r = 0;//相当于队首和队尾指针;
    node S;//存放起点;
    S.x = s;
    S.step = 0;
    map[s] = 1;
    que[r++] = S;//push操作;
    node p;
    while (r > l) {//队列不为空;
        p = que[l++];//提取加Pop操作;
        if (p.x == t) return p.step;//已经找到;
        node q;
        for (int i = 0;i < 3;++i) {//三种情况的循环;
            int nx;
            if (p.x > t) {//超过t之后再增加只会越加越远;
                nx = p.x - 1;
            }
            else if (p.x < t) {
                if (i == 2) {
                    nx = p.x * dir[i];
                }
                else {
                    nx = p.x + dir[i];
                }
            }
            if (nx >= 0 && nx <= 100000 && map[nx] == 0) {//满足条件即加入队列;
                q.x = nx;
                map[nx] = 1;//将该点标为已经访问过;
                q.step = p.step + 1;
                que[r++] = q;
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int s, e;
    while (cin >> s >> e) {
        int ans = bfs(s, e);
        cout << ans << endl;
    }
    return 0;
}

你可能感兴趣的:(hdoj2717 Catch That Cow)