【NOJ1541】【分支限界法】加1乘2平方
阿新 • • 發佈:2018-12-13
1541.加1乘2平方
時限:1000ms 記憶體限制:10000K 總時限:3000ms
描述
給定兩個正整數m、n,問只能做加1、乘2和平方這三種變化,從m變化到n最少需要幾次
輸入
輸入兩個10000以內的正整數m和n,且m小於n
輸出
輸出從m變化到n的最少次數
#include <iostream> #include <queue> #include <math.h> using namespace std; queue <int> q1; int m,n; int step[10001]; //step[i]=x表示變化到i要經歷x步 int used[10001]; //used[i]=1表示數字i已經出現過 int top; //棧頂元素 int main() { cin>>m>>n; q1.push(m); step[m]=0; used[m]=1; while(!q1.empty()) { top=q1.front(); q1.pop(); //+1 if(top+1<=n&&!used[top+1]) { step[top+1]=step[top]+1; used[top+1]=1; if(top+1==n) { //cout<<"+1"<<top+1<<' '<<step[top+1]<<endl; break; } q1.push(top+1); //cout<<top+1<<' '<<step[top+1]<<endl; } //*2 if(top*2<=n&&!used[top*2]) { step[top*2]=step[top]+1; used[top*2]=1; if(top*2==n) { //cout<<"*2"<<top*2<<' '<<step[top*2]<<endl; break; } q1.push(top*2); //cout<<top*2<<' '<<step[top*2]<<endl; } //^2 if(top*top<=n&&!used[top*top]) { step[top*top]=step[top]+1; used[top*top]=1; if(top*top==n) { //cout<<"^2"<<top*top<<' '<<step[top*top]<<endl; break; } q1.push(top*top); //cout<<top*top<<' '<<step[top*top]<<endl; } } cout<<step[n]<<endl; return 0; }