CodeForces-520B Two Buttons [Reverse Thinking|| bfs] Solution

Hello, everyone, welcome to visit Lin Shenshi's blog of No See Deer, the algorithm Xiaobai, records the daily life of learning, and is committed to easy-to-understand problem solving. Meeting is the signing. If there are shortcomings, please give us more advice.

1. Title

Given a natural number, there are two operations:
1. Multiply the number by 2.
2. Subtract 1 from the number.
If the number is not positive after a certain operation, it terminates.
What you have at the beginning is the number n.

Your goal is to get the number m. In order to obtain this result, how many operations does he need at least?

Input format
Input one line, two integers n and m (1 ≤ n, m ≤ 104), separated by spaces.

Output format
Output the minimum number of operations.

Input and output sample
input
2 3
output
2
input
11 1
output
10
sample description In
sample 1, first multiply by 2, then subtract 1.

In sample 2, just subtract one from crazy

2. Thinking (1) Reverse thinking

1. If n>m, m can only be obtained by subtracting one.
2. n<=m, considering reverse thinking, changing n to m requires two operations, n-1 and n*2, then changing from m to n requires two operations, m+1 and m/2, corresponding operations The numbers are the same, but the reverse is more helpful for us to think.
3. If m is an odd number, the m/2 operation cannot be performed, and m+1 is performed to make it an even number. If m is an even number, go directly to m/2, repeat the above operation until n>=m and exit, and add nm to the last operand.

3. Code

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    
    
	int n,m;
	cin>>n>>m;
	int ans=0;
	if(n>m) 
	{
    
    
		ans=n-m;
	}
	else
	{
    
    
		while(n<m) 
	    {
    
    
		  if(m%2==0)
	      {
    
    
	     	m/=2;
	     	ans++;
		  }
		  else
		  {
    
    
		  	 m++;
		  	 ans++;
		  }
		}
		ans+=n-m;
	}
	cout<<ans<<endl;
	return 0;
}

4 ideas (2) bfs

This question is very similar to AcWing 1100. Grab the cow can be said to be a reduced version of that question.
Direct bfs search.

5. Code

#include<iostream>
#include<cstdio>
#include<cstring> 
using namespace std;
const int N=1e4+10;
int q[N];
int dist[N]; 
int n,m;
int bfs()
{
    
    
    memset(dist,-1,sizeof(dist));
    int hh=0,tt=0;
    q[0]=n;
    dist[n]=0;
    while(hh<=tt)
    {
    
    
    	int t=q[hh++];
    	if(t==m)  return dist[m];
    	if(t-1<N&&dist[t-1]==-1)
    	{
    
    
    		dist[t-1]=dist[t]+1;
    		q[++tt]=t-1;
		}
		if(t*2<N&&dist[t*2]==-1)
		{
    
    
			dist[t*2]=dist[t]+1;
			q[++tt]=t*2;
		}
	}
	return -1;
}
int main()
{
    
    
   cin>>n>>m;
   cout<<bfs()<<endl;
   return 0;
}

Guess you like

Origin blog.csdn.net/weixin_45629285/article/details/108911266