搜索算法——加一乘二平方

来源:互联网 发布:linux命令 退出 编辑:程序博客网 时间:2024/05/23 12:01

描述
最简单的队列的使用

给定两个正整数m、n,问只能做加1、乘2和平方这三种变化,从m变化到n最少需要几次
 
输入
输入两个10000以内的正整数m和n,且m小于n
 
输出
输出从m变化到n的最少次数
 
输入样例
1 16
 
输出样例
3

基本思路:套用搜索算法的一般模式即可。


#include <iostream>#include <queue>using namespace std;int m, n, step[10000000];queue<int>q;int bfs();int moveto(int key, int dir);int main(){    cin >> m >> n ;    cout << bfs()-1 << endl;}int bfs(){    step[m] = 1;    q.push(m);    while(!q.empty())    {        int u = q.front();        q.pop();        for(int i = 0; i < 3; i++)        {            int v = moveto(u,i);            if(v == n)            return(step[u]+1);            if( v <= n &&step[v] == 0 )            {                step[v] = step[u] + 1;                q.push(v);            }        }    }    return 0;}int moveto(int key, int dir){    switch(dir)    {        case 0 : key++; break;        case 1 : key = key * 2; break;        case 2 : key = key * key; break;    }    return key;}


1 0