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

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

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

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

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

层次遍历的实现就是通过队列,循环的将队列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;
}

 

posted @ 2019-04-14 23:49  whalelife  阅读(825)  评论(0编辑  收藏  举报