04.05-DIV+MOD

原题链接

给定一个式子: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.

inputoutput
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的值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值