题意
FJ抓奶牛,FJ的位置为N(0≤N≤100,000),奶牛的位置为K(0≤N≤100,000)。有三种移动方式抓奶牛:N-1/分钟,N+1/分钟,N*2/分钟。奶牛不会动,问FJ抓住奶牛至少需要多少分钟?
要点
1,这是一道简单的BFS题。
2,注意记录走过点,不然会超时。
代码
#include<stdio.h>
#include<queue>
const int max = 100010;
int visited[max];
struct node {
int cur;
int dis;
};
int bfs(int n, int k) {
if (n == k) return 0;
std::queue<node> q;
node head;
head.cur = n;
head.dis = 0;
q.push(head);
visited[n] = 1;
while (!q.empty()) {
node front = q.front();
q.pop();
node newnode;
newnode.dis = front.dis + 1;
for (int i = 0; i < 3; ++i) {
if (0 == i) {
newnode.cur = front.cur - 1;
}
else if (1 == i) {
newnode.cur = front.cur + 1;
}
else {
newnode.cur = front.cur << 1;
}
if (newnode.cur == k) return newnode.dis;
else if (newnode.cur >= 0 && newnode.cur <= max&&!visited[newnode.cur]) {
q.push(newnode);
visited[newnode.cur] = 1;
}
}
}
return 0;
}
int main() {
int n, k;
while (~scanf("%d%d", &n, &k) && n >= 0 && n <= max&&k >= 0 && k <= max) {
if (n >= k) printf("%d\n", n - k);
else {
memset(visited, 0, sizeof(visited));
printf("%d\n", bfs(n, k));
}
}
return 0;
}