洛谷P7909 [CSP-J 2021] 分糖果 题解

本题做法

  • 数学。

思路

这题需要把上下界 \(L\)\(R\) 分成 2 种情况讨论。

情况 1:\(R-L<n\)

当这种情况时,代表 \(L\)\(R\) 并没有完全覆盖 1 个以上的 2 个相邻 \(n\) 的倍数之间的区间,当发生这种情况时,又要分成 2 种情况来讨论。

情况 1.1:\(⌊L\div n⌋\neq⌊R\div n⌋\)

这种情况代表的是 \(L\)\(R\) 并不处在同一个 \(n\) 倍数区间内,他们之间存在 \(k+n-1(k为n的倍数)\) 这个数,此时得到的最大奖励就是 \(n-1\)

情况 1.2:\(⌊L\div n⌋=⌊R\div n⌋\)

这种情况代表的是 \(L\)\(R\) 处在同一个 \(n\) 倍数区间内,他们之间存在的最大对 \(n\) 取余的余数就是 \(\max(L\bmod n,R\bmod n)\).

情况 2:\(R-L\ge n\)

这种情况代表的是 \(L\)\(R\) 已经覆盖了 1 个以上的 2 个相邻的 \(n\) 倍数之间的区间,此时最大的奖励数量(也就是对 \(n\) 取余数)就是 \(n-1\)

代码

#include<bits/stdc++.h>

using namespace std;

const int INF=0x3f3f3f3f;
const double EPS=1e-8;

long long n,l,r;

int main(){
	ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
	cin>>n>>l>>r;
	if(r-l<n){
		if(l/n==r/n){
			cout<<max(l%n,r%n)<<endl;
		}else{
			cout<<n-1<<endl;
		}
	}else{
		cout<<n-1<<endl;
	}
	return 0;
}
posted @ 2025-06-27 13:21  2789617221guo  阅读(80)  评论(0)    收藏  举报