HDU 5802 Windows 10

Problem Description

Long long ago, there was an old monk living on the top of a mountain. Recently, our old monk found the operating system of his computer was updating to windows 10 automatically and he even can’t just stop it !!
With a peaceful heart, the old monk gradually accepted this reality because his favorite comic LoveLive doesn’t depend on the OS. Today, like the past day, he opens bilibili and wants to watch it again. But he observes that the voice of his computer can be represented as dB and always be integer.
Because he is old, he always needs 1 second to press a button. He found that if he wants to take up the voice, he only can add 1 dB in each second by pressing the up button. But when he wants to take down the voice, he can press the down button, and if the last second he presses the down button and the voice decrease x dB, then in this second, it will decrease 2 * x dB. But if the last second he chooses to have a rest or press the up button, in this second he can only decrease the voice by 1 dB.
Now, he wonders the minimal seconds he should take to adjust the voice from p dB to q dB. Please be careful, because of some strange reasons, the voice of his computer can larger than any dB but can’t be less than 0 dB.

Input

First line contains a number T (1≤T≤300000),cases number.
Next T line,each line contains two numbers p and q (0≤p,q≤109)

Output

The minimal seconds he should take

Sample Input

1
2
3
2
1 5
7 3

Sample Output

1
2
4
4

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>

using namespace std;

int p, q;

int dfs(int cur, int step, int stop)///现在位置,已走步数,停顿次数
{
int cnt = 0;
while(cur - (1<<cnt) + 1 > q) cnt++;
step += cnt;
if(cur - (1<<cnt) + 1 == q) return step;
int up = q - max(0, cur - (1<<cnt) + 1);///需要往回走多少步
int tmp = step + max(up-stop, 0);///通过把之前的停顿换成向上一步来减少之后向上的步数
return min(tmp, dfs(cur - (1<<(cnt-1))+1, step, stop + 1));
}

int main()
{
int ca;
int ans;
scanf("%d", &ca);
while(ca--)
{
scanf("%d%d", &p, &q);
if(p <= q)
ans = q - p;
else
ans = dfs(p, 0, 0);
printf("%d\n", ans);
}
return 0;
}