1到n的最小步数

 

1到n的最小步数

 Time Limit: 1 Sec  Memory Limit: 128 MB

给你一个数n,让你求从1到n的最小步数是多少。

对于当前的数x有三种操作:

1:  x+1

2:  x-1

3:  x*2

Input

测试数据为多组,对于每组测试数据:(大约1000组)

输入一个正整数n(1 <= n <= 1000000)

Output

对于每组测试数据输入从1到n的最小步数ans

Sample Input

3
8

Sample Output

2
3

这道题就是BFS模板题,但是又有点区别,测试数据组数比较多,直接写容易超时,所以要用到预处理
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>

using namespace std;
const int maxn=1e6+100;
int cnt[maxn*2];
int n,t;

void bfs(){
    queue<int>q;
    q.push(1);
    while(!q.empty()){
        int x=q.front(),xx;
        if(t==maxn)
            return ;
        for(int i=0;i<3;i++){    ///进行  +1  -1  *2   3种操作
            if(i==0){
                xx=x+1;
            }
            else if(i==1){
                xx=x-1;
            }
            else{
                xx=x*2;
            }
            if(xx<0||xx>maxn||cnt[xx]||xx==1)  ///判断操作后是否满足条件
                continue;
            cnt[xx]=cnt[x]+1;  ///操作数 + 1
            q.push(xx);  
            t++;         ///直接 搜索1e6次
        }
        q.pop();
    }
}

int main(){
    bfs();
    while(~scanf("%d",&n)){
        printf("%d\n",cnt[n]);
    }
    return 0;
}
 
 

 



转载于:https://www.cnblogs.com/Y292/p/9148257.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值