Title: Give you two numbers, N (for farmer John) and K (for his cow's position). John has three ways of moving each time. 1. Move one grid to the left, 2. Move one grid to the right, 3. Move to the position of the subscript twice the current position. The cow is stationary. Ask how many steps John needs to take to get to the cow's position at least.
Analysis: Because it is to find the minimum number of steps, so we can directly use BFS to solve this problem in review and write a RE for a long time, and finally found a problem. If we first judge whether the current subscript is marked or not, we need to open the size of the array to twice the requirements of the topic, but if we first judge whether it is beyond the bounds, for & & operation, the current side is not. When it is established, the latter operation will not be performed, so if it is first judged whether it crosses the boundary, it will not be RE.
#include<map> #include<set> #include<cmath> #include<queue> #include<stack> #include<cstdio> #include<vector> #include<utility> #include<cctype> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> #define inf 0x3f3f3f3f #define Clear(x) memset(x,0,sizeof(x)) #define fup(i,a,b) for(int i=a;i<b;i++) #define rfup(i,a,b) for(int i=a;i<=b;i++) #define fdn(i,a,b) for(int i=a;i>b;i--) #define rfdn(i,a,b) for(int i=a;i>=b;i--) typedef long long ll; using namespace std; const double pi=acos(-1.0); const int maxn = 1e5+5; int N,K; int vis[maxn]; struct node{ int x,step; }; node vs,zb,nzb; int BFS() { Clear(vis); queue<node>q; while(!q.empty()) q.pop(); vs.x=N,vs.step=0; vis[N]=1; q.push(vs); while(!q.empty()) { zb = q.front(); q.pop(); if(zb.x==K) return zb.step; if(zb.x-1>=0&&!vis[zb.x-1]) { vis[zb.x-1] = 1; nzb.x = zb.x-1; nzb.step = zb.step+1; q.push(nzb); } if(zb.x+1<=100000&&!vis[zb.x+1]) { vis[zb.x+1] = 1; nzb.x = zb.x+1; nzb.step = zb.step+1; q.push(nzb); } if(zb.x*2<=100000&&!vis[zb.x*2]) { vis[zb.x*2] = 1; nzb.x = zb.x*2; nzb.step = zb.step +1; q.push(nzb); } } return 0; } int main() { while(scanf("%d%d",&N,&K)==2) { printf("%d\n",BFS()); } return 0; }