很简单的一道广度遍历题目
1 #include <stdio.h>
2 #define up_bound 100000
3 #define down_bound 0
4 int Q[100010],dist[100010]={0};
5 int vis[100010]={0};
6
7 int bfs(int n,int k){
8 int front=0,rear=1;
9 Q[front]=n;
10 vis[n]=1;
11 while(front<rear){
12 int x=Q[front];
13 if(x==k)
14 break;
15 if(vis[x-1]==0 && x>down_bound){
16 vis[x-1]=1;
17 dist[rear]=dist[front]+1;
18 Q[rear++]=x-1;
19 }
20 if(vis[x+1]==0 && x<up_bound){
21 vis[x+1]=1;
22 dist[rear]=dist[front]+1;
23 Q[rear++]=x+1;
24 }
25 if(vis[2*x]==0 && x>down_bound && x<=up_bound/2){
26 vis[2*x]=1;
27 dist[rear]=dist[front]+1;
28 Q[rear++]=2*x;
29 }
30 front++;
31 }
32 return dist[front];
33 }
34 int main(){
35 int N,K,ans;
36 scanf("%d %d",&N,&K);
37 if(N>K) ans=N-K;
38 else ans=bfs(N,K);
39 printf("%d\n",ans);
40 }