题目描述
Input
Output
Sample Input
4 6
10 1
Sample Output
2
9
Note
#include <iostream>
#include<queue>
using namespace std;
const int N = 10010;
int ans[N];
int n,m;
void bfs(int a,int b)
{
queue<int>q;
q.push(a);
while(!q.empty()){
int st=q.front();
q.pop();
if(!ans[st-1]&&st-1>0)//判断在数据范围内,且第一次存储
{
ans[st-1]=ans[st]+1;
q.push(st-1);
}
if(!ans[st*2]&&st*2<= N)
{
ans[st*2]=ans[st]+1;
q.push(st*2);
}
}
cout<<ans[m]<<endl;//输出即最短路
}
int main()
{
cin>>n>>m;
bfs(n,m);
return 0;
}
题目大意
输入两个整数n m,对n进行一系列操作变成m,求最少操作次数。
每次操作将n减1或乘2。
思路
简简单单BFS,将n可能变化全都存入答案列,注意数据范围。