AcWing 4300. 两种操作 (BFS搜索最少次数)

给定一个正整数 nn,我们希望你可以通过一系列的操作,将其变为另一个正整数 mm。

操作共分两种:

  1. 将当前的数乘以 22。
  2. 将当前的数减去 11。

要求,在变换过程中,数字始终为正

请你计算,所需要的最少操作次数。

输入格式

一行,两个不同的正整数 nn 和 mm。

输出格式

一个整数,表示所需的最少操作次数。

数据范围

前 66 个测试点满足 1≤n,m≤101≤n,m≤10。
所有测试点满足 1≤n,m≤100001≤n,m≤10000。

输入样例1:

4 6

输出样例1:

2

输入样例2:

10 1

输出样例2:

9

代码如下:

#include<iostream>
#include<queue>
#include<algorithm> 
#include<cstring>
using namespace std;

int n, m;
struct point{
	int x;
	int step=0;
};
queue<point> r;
int vis[200010];

int main()
{
	ios::sync_with_stdio(false);
	cout.tie(NULL);
	
	memset(vis, 0, sizeof(vis));
	cin >> n >> m;
	
	point start;
	start.x = n;
	start.step = 0;
	vis[n] = 1;
	r.push(start);
	
	while(!r.empty())
	{
		int xx = r.front().x;
		if(xx == m){
			cout<< r.front().step;
			break;
		}
	
		for(int i = 0; i < 2; i ++)
		{
			int y;
			if(i == 0 && xx < m)	y = 2 * xx;
			else{
				y = xx - 1;
				if(y <= 0){
					continue;
				}
			}	
			
			if(vis[y] == 0){
			point temp;
			temp.x = y;
			temp.step = r.front().step + 1;
			vis[y] = 1;
			r.push(temp);
			}
			
		}
		r.pop(); 
	}
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值