当前位置:网站首页>AcWing 4300. Two operations (minimum number of BFS searches)

AcWing 4300. Two operations (minimum number of BFS searches)

2022-07-06 22:56:00 GHOSTANDBREAD

Given a positive integer  nn, We hope you can through a series of operations , Change it to another positive integer  mm.

There are two kinds of operations :

  1. Multiply the current number by  22.
  2. Subtract... From the current number  11.

requirement , During the transformation , The number is always positive .

Please calculate , The minimum number of operations required .

Input format

a line , Two different positive integers  nn  and  mm.

Output format

An integer , Indicates the minimum number of operations required .

Data range

front  66  Test points meet  1≤n,m≤101≤n,m≤10.
All test points meet  1≤n,m≤100001≤n,m≤10000.

sample input 1:

4 6

sample output 1:

2

sample input 2:

10 1

sample output 2:

9

The code is as follows :

#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;
}

原网站

版权声明
本文为[GHOSTANDBREAD]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131041487970.html