POJ3278 Catch That Cow bfs

跟杭电的奇怪的楼梯非常想。

代码如下:

#include <cstdio>
#include <queue>
using namespace std;

struct Node
{
    int x, t;
}e[100005], pos;

int N, K, front, tail, hash[100005];

void getnewpos(int x, int a[])
{
    a[0] = x - 1;
    a[1] = x + 1;
    a[2] = x << 1;    
}

int bfs()
{ 
    memset(hash, 0, sizeof (hash));
    hash[N] = 1;
    int x[3];
    front = 0, tail = 1;
    e[tail].x = N, e[tail].t = 0;
    while (front != tail) {
        pos = e[++front];
        getnewpos(pos.x, x);
        for (int i = 0; i < 3; ++i) {
            if (!hash[x[i]] && x[i] >= 0 && x[i] <= 100000) {
                hash[x[i]] = 1;
                if (x[i] == K) {
                    return pos.t + 1;
                }
                else {
                    ++tail;
                    e[tail].x = x[i];
                    e[tail].t = pos.t + 1;
                }
            }
        }
    }
}

int main()
{
    while (scanf("%d %d", &N, &K) == 2) {
        printf("%d\n", bfs());
    }
}
原文地址:https://www.cnblogs.com/Lyush/p/2590435.html