P7909 [CSP-J 2021] 分糖果

· · 题解

题意

找到一个数 k,使 L\le k\le R,且 k\bmod n 最大,输出这个最大值。

分析

显然 k\bmod n 的最大值为 n-1,于是我们找到 L\sim R 中最大的 n 的倍数 \left\lfloor\frac{R}{n}\right\rfloor\times n,若 \left\lfloor\frac{R}{n}\right\rfloor\times n-1 仍在 L\sim R 中,则答案可取到最大值 n-1。

反之,若不满足上述条件,那么有\left\lfloor\frac{R}{n}\right\rfloor\times n\le L\le R<(\left\lfloor\frac{R}{n}\right\rfloor+1)\times n,此时 R-\left\lfloor\frac{R}{n}\right\rfloor\times n 为最大答案。

代码

#include<bits/stdc++.h>
#define ll long long
using namespace std;
long long read(){
    long long x=0,f=1;char ch=getchar();
    while(!isdigit(ch)){if(ch=='-') f=-1;ch=getchar();}
    while(isdigit(ch)){x=x*10+ch-48;ch=getchar();}
    return x*f;
}
void write(long long x){
    if(x<0) putchar('-'),x=-x;
    if(x>9) write(x/10);
    putchar(x%10+'0');
}
//const int N=;
ll n,l,r;
int main(){
    n=read();l=read();r=read();
    if(r/n*n-1>=l)
        write(n-1);
    else
        write(r-r/n*n);
    return 0;
}