您的位置:首页 > 其它

hdu 2717 Catch That Cow

2013-09-08 12:47 218 查看
       
hdu 2717 Catch That Cow

        广搜.

#include <stdio.h>
#include <queue>
using namespace std;

#define MAX 100005

struct node {
int pos;
int step;
};

int n, k;
bool visited[MAX];

int bfs(int s) {
queue<node> Q;
node start, now, next;
memset(visited, false, sizeof(visited));
start.pos = s;
start.step = 0;
visited[s] = true;
Q.push(start);

while (!Q.empty()) {
now = Q.front();
Q.pop();

if (now.pos + 1 == k || now.pos - 1 == k || now.pos*2 == k) {
return now.step + 1;
}

if (now.pos*2 <= 100000 && !visited[now.pos*2]) {
next.pos = now.pos*2;
next.step = now.step + 1;
visited[next.pos] = true;
Q.push(next);
}

if (now.pos - 1 >= 0 && !visited[now.pos - 1]) {
next.pos = now.pos - 1;
next.step = now.step + 1;
visited[next.pos] = true;
Q.push(next);
}

if (now.pos + 1 <= 100000 && !visited[now.pos + 1]) {
next.pos = now.pos + 1;
next.step = now.step + 1;
visited[next.pos] = true;
Q.push(next);
}
}

return 0;
}

int main() {
int ans;

while (scanf("%d%d", &n, &k) != EOF) {
if (n == k) {
printf("0\n");
} else {
ans = bfs(n);
printf("%d\n", ans);
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: