题目链接:http://poj.org/problem?id=3278
#include <cstdio> #include <queue> #include <string.h> using namespace std; #define MAXN 200000 int key[MAXN];///走到key[i]的步数 bool vis[MAXN];///是否走过 int bfs(int first,int last) { int v; queue<int>q; ///初始化没有走过 memset(vis,false,sizeof(vis)); q.push(first); key[first]=0; vis[first]=true; while(!q.empty()) { v=q.front(); q.pop(); if(v==last) return key[v]; ///向左走 if((v-1)>=0&&(v-1)<MAXN&&!vis[v-1]) { key[v-1]=key[v]+1; vis[v-1]=true; q.push(v-1); } ///向右走 if((v+1)>=0&&(v+1)<MAXN&&!vis[v+1]) { key[v+1]=key[v]+1; vis[v+1]=true; q.push(v+1); } ///跳 if((v*2)>=0&&(v*2)<MAXN&&!vis[v*2]) { key[v*2]=key[v]+1; vis[v*2]=true; q.push(v*2); } } } int main() { int n,k; while(scanf("%d%d",&n,&k)!=EOF) { printf("%d ",bfs(n,k)); } return 0; }