给定一个式子: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.
input | output |
5 1 4 3 5 8 4 6 10 6 1 1000000000 1000000000 10 12 8 | 2 4 5 999999999 5 |
解题思路
这是一道数学题,x可以从[l,r]范围中,找x/a和x%a的最大值。用循环枚举会超时,故我们可以分类讨论寻找规律。不难发现,当l/a=r/a(左端点的商等于右端点)或者虽然不等但是右端点r%a恰好取得余数最大时,在区间[l,r]内,x/a的贡献不变,而余数x%a递增。此时最大值取r/a+r%a。另一种情况,当左右端点的商值不相等并且右端点取不到余数最大值的时候,最大值取(r/a)-1+(a-1),a-1表示余数最大。
#include<bits/stdc++.h>
using namespace std;
void solve()
{
long long l,r,a;
cin>>l>>r>>a;
long long maxx;
long long aa=l/a,bb=r/a,cc=r%a;
if(aa==bb||(r+1)%a==0)
{
maxx=bb+cc;
}
else
{
maxx=bb-1+a-1;
}
cout<<maxx<<endl;
}
int main()
{
int t;
cin>>t;
while(t--)
{
solve();
}
}
另一种方法直接找取得最大时x的值。