这段时间要沉迷刷题一段时间了,就让CSDN陪我一起吧!
一、题目大意
题目的大致意思就是John要去抓奶牛,一开始John在数轴上的位置N,奶牛在数轴上的位置K,然后问John最快可以经过几步把奶牛抓住?
给出Johnson的行走策略:
- 要么可以从X位置走到X+1或X-1
- 要么可以从X位置瞬移到2*X的位置
二、题目思路以及AC代码
这题很明显也是一道BFS的变种,只需根据其给定的行走策略,变化BFS的行走策略即可。
下面给出AC代码:
#include <iostream>
#include <queue>
#define MAXN 100010
using namespace std;
struct Point {
int x;
int step;
};
int N, K;
Point start;
int dx[2] = { -1, 1 };
bool vis[MAXN];
int bfs() {
for (int i = 0; i < MAXN; i++) {
vis[i] = false;
}
queue<Point> q;
q.push(start);
vis[start.x] = true;
while (!q.empty()) {
Point cur = q.front(); q.pop();
for (int i = 0; i < 2; i++) {
int nx = cur.x + dx[i];
if (nx < 0 || nx > 100000) continue;
if (vis[nx]) continue;
if (nx == K)
return cur.step + 1;
vis[nx] = true;
Point next;
next.x = nx;
next.step = cur.step + 1;
q.push(next);
}
int nx = 2 * cur.x;
if (nx >= 0 && nx <= 100000 && !vis[nx]) {
if (nx == K)
return cur.step + 1;
vis[nx] = true;
Point next;
next.x = nx;
next.step = cur.step + 1;
q.push(next);
}
}
return -1;
}
int main()
{
cin >> N >> K;
if (N == K) {
cout << 0 << endl;
}
else {
start.x = N;
start.step = 0;
cout << bfs() << endl;
}
return 0;
}
如果有问题,欢迎大家指正!!!