題目描述
現在有兩種操作:將一個整數*2或者將一個整數-1;
給你兩個整數A,B 請用以上兩種操作把A轉換成B,要求使用次數儘量少,輸出最少操作次數
輸入
輸入包含多組測試數據,對於每組測試數據:
輸入包含一行
第一行:兩個整數A,B
輸出
最少操作次數
樣例輸入
4 6
10 1
樣例輸出
2
9
提示
對於第一個 4 –>3 -> 6 兩步
對於第二個 10->9->8->7……->2->1 九步
注意題中數據範圍!
bfs裏面如果num超過10000的話就不入隊
不要重複命名局部變量和全局變量!
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
int m, n;
struct node
{
int num;
int step;
};
node New,now;
node first;
bool vis[10000];//first
int bfs()
{
queue<node>q;
q.push(first);
vis[first.num] = true;
while(!q.empty())
{
now = q.front();
q.pop();
New.num = now.num - 1;
New.step = now.step + 1;
if(!vis[New.num] && New.num <= 10000)//second
{
q.push(New);
if(New.num == n)
return New.step;
vis[New.num] = true;
}
New.num = now.num * 2;
New.step = now.step + 1;
if(!vis[New.num] && New.num <= 10000) //thired
{
q.push(New);
if(New.num == n)
return New.step;
vis[New.num] = true;
}
}
return -1;
}
int main()
{
int i,j;
while(scanf("%d%d", &m, &n) != EOF)
{
memset(vis, false, sizeof(vis));
first.num = m;
first.step = 0;
if (m > n) //forth
{
cout<<m-n<<endl;
continue;
}
int ans = bfs();
if(ans > 0)
printf("%d\n", ans);
}
return 0;
}