今天又来水文章了,嗯,一个题吧:
给定一个式子:f(x)=x/a+x%a(其中x/a向下取整)
已知a是给定的,x可以从[l,r]范围中选择一个,要求计算出最大的f(x)
Input
第一行给定一个t(1<=t<=1e4)表示有t组样例
对于每一组样例给定l,r,a(1<=l<=r<=1e9,1<=a<=1e9)
The first line of input data contains an integer tt (1 \le t \le 10^41≤t≤104) — the number of input test cases.
This is followed by tt lines, each of which contains three integers l_ili, r_iri and a_iai (1 \le l_i \le r_i \le 10^9, 1 \le a_i \le 10^91≤li≤ri≤109,1≤ai≤109) — the left and right boundaries of the segment and the fixed value of aa.
Output
输出最大的f(x),x为[l,r]范围内的一个数
For each test case, output one number on a separate line — the maximum value of the function on a given segment for a given aa.
Sample 1
Inputcopy | Outputcopy |
---|---|
5 1 4 3 5 8 4 6 10 6 1 1000000000 1000000000 10 12 8 | 2 4 5 999999999 5 |
Note
In the first sample:
- f_3(1) = \left\lfloor\frac{1}{3}\right\rfloor + 1 \bmod 3 = 0 + 1 = 1f3(1)=⌊31⌋+1mod3=0+1=1,
- f_3(2) = \left\lfloor\frac{2}{3}\right\rfloor + 2 \bmod 3 = 0 + 2 = 2f3(2)=⌊32⌋+2mod3=0+2=2,
- f_3(3) = \left\lfloor\frac{3}{3}\right\rfloor + 3 \bmod 3 = 1 + 0 = 1f3(3)=⌊33⌋+3mod3=1+0=1,
- f_3(4) = \left\lfloor\frac{4}{3}\right\rfloor + 4 \bmod 3 = 1 + 1 = 2f3(4)=⌊34⌋+4mod3=1+1=2
As an answer, obviously, f_3(2)f3(2) and f_3(4)f3(4) are suitable.
今天测的这道题,我写了,两个半小时,刚开始是拼命找规律,然后一直没想全,在最后三十分钟终于想全了但似乎时间超限,气煞我了,先看我写了两个半多小时的代码:
#include<stdio.h>
long long L,R,A;
long long fun(long long x)
{
return x/A+x%A;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%lld %lld %lld",&L,&R,&A);
long long i;
for(i=R; i>=L; i--)
{
if(A>=3&&i%A==0&&L<R&&L!=i)
{
long long c=(fun(R)>=fun(i-1))?fun(R):fun(i-1); printf("%lld\n",c); break;
}
else if(A>3&&i%A==0)
{
printf("%lld\n",fun(R));
break;
}
if((A==3&&L<=R)||A<3)
{
printf("%lld\n",fun(R));
break;
}
}
if(i==L-1)
{
printf("%lld\n",fun(R)); //不能break
}
}
return 0;
}
然后听学长讲课之后才知道直接用一个公式就行了,越想越气,整整三页纸的规律,还比不过一个公式TAT,对此我们进行分析,你看如果要是这个公式最大的话就要分别使x/a,和x%a最大,单独一个x/a还好,直接让x取最大值就行了,但是这个x%a,就不能这么搞了,可以想想,怎样才会让余数最大,不就是让它的余数尽可能的接近a-1嘛,因为a-1余数最大,只要是x接近a-1就行(x可能很大很大但余数是a-1的),所以你可以满足这样的要求的x=n*a+a-1都可以,然后取最大,然后就会得到下面的代码
#include<stdio.h>
long long a,L,R;
long long fun(long long x)
{
return x/a+x%a;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%lld %lld %lld",&L,&R,&a);
long long x;
x=R-R%a-1;
if(x<=R&&x>=L&&fun(x)>fun(R))
printf("%lld\n",fun(x));
else
printf("%lld\n",fun(R));
}
return 0;
}
然后我们来验证一下这个公式的合理性(其实是作者能力不济不会直接推出来):
这个r-r%a-1;本来要使这个x%a最大的话满足上面所说的,但如果刚好r就满足的话,当然就取他的最大值r咯,因此我们来看一下,这时候x%a就是为a-1,再继续这个个公式就变成了r-a+1-1=r-a,明显不对,(这就为后面取最大值奠定了基础)因为这个公式是求r下面的次大值,是保证了r一定不为那个满足的条件才有的,来理解一下哈,
这就结束了?不甘心,再来点鸡汤醒脑:
要把所有的夜都归还给星河,要把所有的春光归还给疏疏篱落,把所有的庸庸迷离与不前,归还给过去的我,明日之我,胸中有丘壑,立马振山河!