poj-3278

31 篇文章 0 订阅
// 1152K    47MS    G++
#include <cstdio>
#include <queue>
#include <cstring>

#define MAX 100001

using namespace std;

struct Pos {
    int x;
    int time;
};

typedef struct Pos Pos;

queue<Pos> BFSQueue;

int Bx;
int Ex;

int BFSFlag[MAX];

int BFS() {
    while(BFSQueue.size()) {
        BFSQueue.pop();
    }

    memset(BFSFlag, 0, sizeof(BFSFlag));

    Pos beginPos;
    beginPos.x = Bx;
    beginPos.time = 0;
    BFSFlag[Bx] = 1;
    BFSQueue.push(beginPos);
    while(BFSQueue.size()) {
        Pos curPos = BFSQueue.front();
        BFSQueue.pop();
        int curX = curPos.x;
        int curTime = curPos.time;

        //walk x -1
        if (curX - 1 >= 0 && !BFSFlag[curX-1]) {
            BFSFlag[curX-1] = 1;
            if (curX-1 == Ex) {
                return curTime + 1;
            } else {
                Pos newPos;
                newPos.x = curX-1;
                newPos.time =curTime + 1;
                BFSQueue.push(newPos);
            }
        }

        //walk x + 1
        if (curX + 1 <= 100000 && !BFSFlag[curX+1]) {
            BFSFlag[curX+1] = 1;
            if (curX+1 == Ex) {
                return curTime + 1;
            } else {
                Pos newPos;
                newPos.x = curX+1;
                newPos.time =curTime + 1;
                BFSQueue.push(newPos);
            }
        }

        // teleport
        int newX = 2*curX;
        if (newX <= 100000 && !BFSFlag[newX]) {
            BFSFlag[newX] = 1;
            if (newX == Ex) {
                return curTime + 1;
            } else {
                Pos newPos;
                newPos.x = newX;
                newPos.time =curTime + 1;
                BFSQueue.push(newPos);
            }
        }

    }
    return -1;
}

void solve() {
    if (Bx == Ex) {
        printf("0\n");
        return;
    }
    int res = BFS();
    printf("%d\n", res);
}

int main() {
    while(scanf("%d %d", &Bx, &Ex) != EOF) {
        solve();
    }
}


测试数据:http://cerberus.delos.com:790/TESTDATA/OPEN07_9.htm

其实是一道简单的DFS水题,连二维都直接给简化成一维了,

不过不小心WA了两次,一次是没有注意最大的100000,还按照之前的习惯,给开了大一些的数组(100010),其实也没错,只是后边判断越界不应该用100010(低级错误),然后就是又忽略了0这个位置,以为最小就是1,这样判断最小越界时用的是1而不是0。。。,都是些2B错误。

其他的简单,一个每次有3种选择的BFS,到达cow的位置return就行了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值