农夫在x位置,下一秒可以到x-1, x+1, 2x,问最少多少步可以到k
*解法:最少步数bfs
要注意的细节蛮多的,写在注释里了
#include <iostream> #include <cstdio> #include <cstring> #include <queue> using namespace std; queue<int> q; int vis[200005], arr[200005]; void go(int n, int k) { q.push(n); vis[n] = 1; int flag = 0; while(!q.empty()) { if(flag) break; int head = q.front(); q.pop(); int direct[3] = {1, -1, head}; if(head == k) return; for(int i = 0; i < 3; i++) { int next = head + direct[i]; if(next >= 0 && next <= 200000 && !vis[next])//坐标一共有1e5但是可以移动到2x 所以next<=2e5;然后next可能小于0,vis[next]直接RE,所以把vis[next]放在最后,先判next>= 0 { q.push(next); vis[next] = 1; arr[next] = arr[head] + 1; } if(next == k) flag = 1; } } return; } int main() { int n, k; while(scanf("%d %d", &n, &k) != EOF) { while(!q.empty()) q.pop(); memset(vis, 0, sizeof(vis)); memset(arr, 0, sizeof(arr)); go(n, k); printf("%d\n", arr[k]); } return 0; }