x变成y的最少操作次数(层次遍历)

时间:2023-03-08 18:31:59

输入x,y,x为源数字,y为目标值。输出x变成y的最少操作次数。

x每次可以执行三种操作:-1 、 +1 、 x2;

如 x=5,y=8:5-1=4,4x2=8;所以输出结果为2(次操作)。

可以发现用树形结构保存,并用层次遍历的方式找最简单。

x变成y的最少操作次数(层次遍历)

层次遍历的实现就是通过队列,循环的将队列front的节点从队列中拿出来,将其儿子节点放入队列后……

#include <iostream>
#include <queue>
using namespace std;
struct node{
int num; //数值
int level; //层数
node(int x,int y):num(x),level(y){}
}; int f(int a,int b){
if(a==b) return ;
queue<node> q;
node aa(a,);
q.push(aa);
while(!q.empty()){
node top = q.front();
q.pop();
if(top.num == b)
return top.level;
q.push(node(top.num-,top.level+));
q.push(node(top.num+,top.level+));
q.push(node(top.num*,top.level+));
}
return -;
}
int main(){
int a,b;
cin>>a>>b;
cout<<f(a,b)<<endl;
}