你收到通知被中南大學錄取了,高興的來到了長沙,很快你就來到了岳麓南路上,已知你的位置是N,中南大學的位置是K。為了去中南大學,你有兩種移動方式:走路或者坐公交。
走路:你可以從位置X移動到X+1或者X-1
搭公交車:你可以從位置X移動到2X
每次走路或者搭公交車所需要的時間都是1分鐘,你想盡快到達中南大學,所需的時間是多少呢?
輸入
對于每組資料,輸入一行,分別是N和K(1<=N,K<=100,000)
輸出
對于每組資料,輸出一行,所需時間
樣例輸入
5 17
樣例輸出
4
我的代碼如下:當輸入樣例K大于20000的時候程式就會停止回應,是怎么回事啊= =
#include<bits/stdc++.h>
using namespace std;
const int maxn=100020;
int mpt[maxn];
int vis[maxn];
int main(void){
int m,n;
while(cin>>m>>n){
queue<int> q;
memset(mpt,0,sizeof(mpt));
memset(vis,0,sizeof(vis));
for(int i=0;i<maxn;i++){
mpt[i]=0;
vis[i]=0;
}
while(!q.empty()){
q.pop();
}
q.push(m);
vis[m]=1;
int temp;
while(!q.empty()){
int ans=q.front();
q.pop();
if(ans==n){
cout<<mpt[ans]<<endl;
break;
}
temp=ans+1;
if(vis[temp]==0 && temp<=100000&&temp>=0){
vis[temp]=1;
mpt[temp]=mpt[ans]+1;
q.push(temp);
}
temp=ans-1;
if(vis[temp]==0 && temp<=100000&&temp>=0){
vis[temp]=1;
mpt[temp]=mpt[ans]+1;
q.push(temp);
}
temp=ans*2;
if(vis[temp]==0 && temp<=100000&&temp>=0){
vis[temp]=1;
mpt[temp]=mpt[ans]+1;
q.push(temp);
}
}
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/95873.html
標籤:新手樂園
下一篇:vs問題解決
