题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5802
题目大意就是增加音量时每次只能增加1,连续降低音量时第一次降低1之后连续的每次都降低上次降低音量的两倍,停顿一秒或在一秒内增加1音量都可打断。求最少要多少时间使得音量从p到q。从题意可得可将数据分为两种 一种为 p<=q 此时所需最少时间为q - p,另一种为p>q,为了时间最短,所以要尽量多的连续减小音量,此时就分成了两个部分,一个是减少到q以下,然后再加到q,另一个是减少到q以上,且再多减一次就减到了q以下,然后再进对新的位置进行上述的操作,取小。因为步骤不断的重复,所以用dfs来写。
min(dfs(now - a[k-1],step + k,stop + 1) , max(q - max(now - a[k] , 0) - stop , 0) + step + k)
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
#define ll long long
ll t,p,q,a[33]={0},m=1;
ll max(ll a,ll b){return a>b?a:b;}
ll dfs(ll now,ll step,ll stop)
{
ll k = 0;
while(now - a[k] > q)
k++;
if(now - a[k] == q)
return step + k;
ll x1 = max(now - a[k] , 0);
x1 = max(q - x1 - stop , 0) + step + k;
return min(dfs(now - a[k-1],step + k,stop + 1) , x1);
}
int main()
{
for(int i=1;i<=30;i++)
a[i] = a[i-1] + m,m *= 2;
scanf("%lld",&t);
while(t--)
{
scanf("%lld%lld",&p,&q);
if(q>=p)
printf("%lld\n",q-p);
else
printf("%lld\n",dfs(p,0,0));
}
return 0;
}