// 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就行了.