广度搜索BFS ///使用数组实现循环队列,注意front和rear。另外有可能出现数组开的比较小的情况,那样 ///会导致数据还没有处理就被刷掉的情况,因此要开的"足够大”。 用for循环实现从三个 ///方向搜索。 用vist数组保存访问情况,已经访问的就不需要再访问。当n大于k时,只能够 ///不断的向左做减一搜索,所以次数为n-k。 #include<stdio.h> #include<string.h> #define MAX 50000 bool vist[100005]; int ti[100005]; int q[MAX]; int n,k,rear,fro; int bfs() { fro=0;rear=0; q[fro]=n; rear++; vist[n]=true; ti[n]=0; int head,next,i; while(fro!=rear) { head=q[fro]; fro=(fro+1)%MAX; for(i=0;i<3;i++) { if(i==0) next=head-1; else if(i==1) next=head+1; else next=head*2; if(next<0||next>100000) continue; if(!vist[next]) { q[rear]=next; rear=(rear+1)%MAX; ti[next]=ti[head]+1; vist[next]=true; } if(next==k) return 0; } } return 0; } int main() { int i; scanf("%d%d",&n,&k); if(n>=k) printf("%d/n",n-k); else { memset(vist,0,sizeof(vist)); bfs(); printf("%d/n",ti[k]); } return 0; } ///使用STL中的queue,学习下, ///queue<int> a; /// a.front() /// a.pop() /// a.push() #include<stdio.h> #include<string.h> #include<queue> using namespace std; queue<int> a; bool vist[100005]; int ti[100005]; int n,k; int bfs() { a.push(n); ti[n]=0; vist[n]=true; int i; while(!a.empty()) { int out=a.front(),next; a.pop(); for(i=1;i<=3;i++) { if(i==1) next=out-1; else if(i==2) next=out+1; else next=out*2; if(next>100000||next<0) continue; if(vist[next]==false) { a.push(next); ti[next]=ti[out]+1; vist[next]=true; } if(next==k) return 0; } } return 0; } int main() { scanf("%d%d",&n,&k); if(n>=k) printf("%d/n",n-k); else { memset(vist,0,sizeof(vist)); bfs(); printf("%d/n",ti[k]); } return 0; }