题意:在一条线上,其实位置N,目的地K,每次行走策略:x + 1,x - 1,x * 2,问最少走到的时间。
思想:方向三个:x + 1,x - 1,x * 2,BFS搜到即可输出,注意,若N == K输出0即可。
#include<stdio.h> #include<string.h> #include<queue> #define MAX_LEN 100005 using namespace std; int map[MAX_LEN]; int N,K; void Find_cow(){ queue<int>q; while(!q.empty()) q.pop(); memset(map,0,sizeof(map)); q.push(N); while(!q.empty()){ N = q.front(); q.pop(); int nxt = N + 1; if(nxt >= 0 && nxt <= 100000 && map[nxt] == 0){ map[nxt] = map[N] + 1; if(nxt == K) return; q.push(nxt); } nxt = N - 1; if(nxt >= 0 && nxt <= 100000 && map[nxt] == 0){ map[nxt] = map[N] + 1; if(nxt == K) return; q.push(nxt); } nxt = N * 2; if(nxt >= 0 && nxt <= 100000 && map[nxt] == 0){ map[nxt] = map[N] +1; if(nxt == K) return; q.push(nxt); } } } int main() { while(~scanf("%d%d",&N,&K)){ if(N == K){ printf("0\n"); continue; } Find_cow(); printf("%d\n",map[K]); } return 0; }