题目很简单,直接bfs,只是有一点要注意,队列开大一点,或者用循环队列,因为每次只有一个出队列,而有三个入队列(有时候少于三个),rear增长的太快了 #include<iostream> using namespace std; #include<cstdio> #define N 100000 int queue[N]; int visited[100005]; int bfs(int st,int ed) { int front=-1,rear=0,i; bool found=false; queue[0]=st; for(i=0;i<=N;i++) visited[i]=-1; visited[st]=0; while(front<rear&&!found) { i=queue[++front]; if(i-1>=0&&visited[i-1]==-1&&!found) { queue[++rear]=i-1; visited[i-1]=visited[i]+1; if(i-1==ed) found=true; } if(i+1<=N&&visited[i+1]==-1&&!found) { queue[++rear]=i+1; visited[i+1]=visited[i]+1; if(i+1==ed) found=true; } if(2*i<=N&&visited[2*i]==-1&&!found) { queue[++rear]=2*i; visited[2*i]=visited[i]+1; if(2*i==ed) found=true; } } return visited[ed]; } int main() { int n,k,h; while(scanf("%d%d",&n,&k)!=EOF) { h=bfs(n,k); printf("%d/n",h); } return 0; }