Not so long ago, Vlad came up with an interesting function:
- f a ( x ) = ⌊ x a ⌋ + x f_a(x)=⌊\frac xa⌋+x fa(x)=⌊ax⌋+x mod a a a, where ⌊ x a ⌋ ⌊\frac xa⌋ ⌊ax⌋ is x a x_a xa, rounded down, x x x mod a a a — the remainder of the integer division of x x x by a a a.
For example, with a = 3 a=3 a=3 and x = 11 x=11 x=11, the value f 3 ( 11 ) = ⌊ 11 3 ⌋ + 11 m o d 3 = 3 + 2 = 5 f_3(11)=⌊\frac{11}3⌋+11mod3=3+2=5 f3(11)=⌊311⌋+11mod3=3+2=5.
The number a a a is fixed and known to Vlad. Help Vlad find the maximum value of f a ( x ) f_a(x) fa(x) if x x x can take any integer value from l l l to r r r inclusive ( l ≤ x ≤ r ) (l≤x≤r) (l≤x≤r).Input
The first line of input data contains an integer t ( 1 ≤ t ≤ 1 0 4 ) t (1≤t≤10^4) t(1≤t≤104) — the number of input test cases.
This is followed by t lines, each of which contains three integers l i , r i l_i, r_i li,ri and a i ( 1 ≤ l i ≤ r i ≤ 1 0 9 , 1 ≤ a i ≤ 1 0 9 ) a_i (1≤l_i≤r_i≤10^9,1≤a_i≤10^9) ai(1≤li≤ri≤109,1≤ai≤109) — the left and right boundaries of the segment and the fixed value of a a a.
Output
For each test case, output one number on a separate line — the maximum value of the function on a given segment for a given a a a.
Example
input5 1 4 3 5 8 4 6 10 6 1 1000000000 1000000000 10 12 8
output
2 4 5 999999999 5
Note
In the first sample:
- f 3 ( 1 ) = ⌊ 1 3 ⌋ + 1 m o d 3 = 0 + 1 = 1 f_3(1)=⌊\frac13⌋+1mod3=0+1=1 f3(1)=⌊31⌋+1mod3=0+1=1,
- f 3 ( 2 ) = ⌊ 2 3 ⌋ + 2 m o d 3 = 0 + 2 = 2 f_3(2)=⌊\frac23⌋+2mod3=0+2=2 f3(2)=⌊32⌋+2mod3=0+2=2,
- f 3 ( 3 ) = ⌊ 3 3 ⌋ + 3 m o d 3 = 1 + 0 = 1 f_3(3)=⌊\frac33⌋+3mod3=1+0=1 f3(3)=⌊33⌋+3mod3=1+0=1,
- f 3 ( 4 ) = ⌊ 4 3 ⌋ + 4 m o d 3 = 1 + 1 = 2 f_3(4)=⌊\frac43⌋+4mod3=1+1=2 f3(4)=⌊34⌋+4mod3=1+1=2
As an answer, obviously, f 3 ( 2 ) f_3(2) f3(2) and f 3 ( 4 ) f_3(4) f3(4) are suitable.
题目大意:
就是找出 i ∈ [ l , r ] i \in [l, r] i∈[l,r], i i i 整除 a a a 向下取整 + i i i m o d mod mod a a a 后的最大值。
解题思路:
先记录 f a ( r ) = ⌊ r a ⌋ + r f_a(r)=⌊\frac ra⌋+r fa(r)=⌊ar⌋+r m o d mod mod a a a 求出来的值,因为 右边界 / a 右边界/a 右边界/a 的商最大。然后就是找出比 r r r 小的且 m o d mod mod a a a 后的余数最大的那个值就是 r / a ∗ a − 1 r/a*a-1 r/a∗a−1,判断它是否在 [ l , r ] [l, r] [l,r] 内,如果在给定的区间内那么最大值则在 f a ( r ) f_a(r) fa(r) 和 f a ( r / a ∗ a − 1 ) f_a(r/a*a-1) fa(r/a∗a−1) 之中,否则为 f a ( r ) f_a(r) fa(r)。
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t; cin>>t;
while(t--)
{
int l, r, a;
cin>>l>>r>>a;
int ans = r/a + r%a; //在 r 的值
if(r/a*a-1 >= l) //若区间内存在比 r 小的且 mod a 后的余数最大的数
ans = max(ans, r/a-1 + a-1);
//比r/a小1所以商为 r/a-1 , 余数为 a-1 时余数才最大
cout<<ans<<'\n';
}
return 0;
}