http://acm.hdu.edu.cn/showproblem.php?pid=2717
基本BFS
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <queue>
5 using namespace std;
6 int N,K;
7 int degree[100002];
8 queue<int> Q;
9 void bfs()
10 {
11 while(!Q.empty()){
12 int cur=Q.front();
13 Q.pop();
14 if(cur==K)
15 break;
16 if(cur-1>=0&°ree[cur-1]==0){
17 degree[cur-1]=degree[cur]+1;
18 Q.push(cur-1);
19 }
20 if(cur+1<=100000&°ree[cur+1]==0){
21 degree[cur+1]=degree[cur]+1;
22 Q.push(cur+1);
23 }
24 if(cur*2<=100000&°ree[2*cur]==0){
25 degree[2*cur]=degree[cur]+1;
26 Q.push(2*cur);
27 }
28 }
29 }
30
31
32 int main()
33 {
34 while(scanf("%d%d",&N,&K)!=EOF){
35 int i;
36 for(i=0;i<100002;i++){
37 degree[i]=0;
38 }
39 while(!Q.empty())
40 Q.pop();
41
42 Q.push(N);
43 bfs();
44 printf("%d\n",degree[K]);
45 }
46 }