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

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

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

如 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 0;
    queue<node> q;
    node aa(a,0);
    q.push(aa);
    while(!q.empty()){
        node top = q.front();
        q.pop();
        if(top.num == b)
            return top.level;
        q.push(node(top.num-1,top.level+1));
        q.push(node(top.num+1,top.level+1));
        q.push(node(top.num*2,top.level+1));
    }
    return -1;
}
int main(){
    int a,b;
    cin>>a>>b;
    cout<<f(a,b)<<endl;
}

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄