程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> CF 520B Two Buttons

CF 520B Two Buttons

編輯:關於C++

 

題面:

 

 

B. Two Buttons time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output

Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at some point the number stops being positive, the device breaks down. The display can show arbitrarily large numbers. Initially, the display shows number n.

Bob wants to get number m on the display. What minimum number of clicks he has to make in order to achieve this result?

Input

The first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 104), separated by a space .

Output

Print a single number — the minimum number of times one needs to push the button required to get the number m out of number n.

Sample test(s) input
4 6
output
2
input
10 1
output
9
Note

In the first example you need to push the blue button once, and then push the red button once.

In the second example, doubling the number is unnecessary, so we need to push the blue button nine times.


 

 

解題:

法一:

一開始看到這題,感覺似曾相識。感覺可能可以寫,最初的想法是這樣的,n>=m,直接輸出n-m。當n

 

代碼:

 

#include 
using namespace std;
int main()
{
	int n,m,cnt=0,t,ans=0,last;
	cin>>n>>m;
	if(n>=m)cout<n)
		{
			if(m%2==0)
			{
				ans++;
				m/=2; 
			}
			else
			{
				m=(m+1)/2;
				ans+=2;
			}
		}
		ans+=(n-m);
		cout<

 

法二:

看了一篇題解,說是spfa爆搜,頓時給跪了。感覺好奇怪,我也沒看具體題解,想了一下,是不是建一張圖,10000個數,減法由x到x-1建立一條權值為1的邊,乘法由n到2*n建立一條權值為1的邊,最後只要搜索n到m的最短路就好了。這是我自己的想法,感覺很巧妙,但是不會超復雜度嗎?然而邊不是矩陣存儲的,因為10000個數,最多不會超過20000條邊。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved