題面:
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?
InputThe first and the only line of the input contains two distinct integers n and m (1 ≤ n, m ≤ 104), separated by a space .
OutputPrint 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) input4 6output
2input
10 1output
9Note
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
代碼:
#includeusing 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條邊。