题解:AT_abc443_g [ABC443G] Another Mod of Linear Problem

· · 题解

模板欸。

先转换为 X_k \le k 的形式。

考虑利用 a \bmod b=a-b\lfloor \frac{a}{b} \rfloor,将原式变成 k(A-1)+B -1 < M \lfloor \frac{kA+B}{M} \rfloor。

将 M 除过去,于是变成了 \lfloor \frac{k(A-1)+B-1}{M} \rfloor < \lfloor \frac{kA+B}{M} \rfloor,然后让左边 +1,变成 \lfloor \frac{k(A-1)+B-1+M}{M} \rfloor \le \lfloor \frac{kA+B}{M} \rfloor

注意到左式减右式一定 \le 1,于是答案就是 \displaystyle \sum_{i=0}^{N-1} \lfloor \frac{k(A-1)+B+M-1}{M} \rfloor-\lfloor \frac{kA+B}{M} \rfloor 了。

这是经典的类欧的形式,直接做就好了,注意特判 A=0 的情况,为 \min(n,B)。

:::success[code]

#include<bits/stdc++.h>
#define big __int128
#define int long long
using namespace std;
const int N=1e6+5;
inline int calc(int n,int m,int a,int b)
{
    int ans=0;
    while(1)
    {
        if(a>=m)
        {
            int q=a/m;
            big add=big(q)*big(n)*big(n-1)/2;
            ans+=add;
            a%=m;
        }
        if(b>=m)
        {
            int q=b/m;
            ans+=q*n;
            b%=m;
        }
        big lst=big(a)*n+b;
        if(lst<m)
            break;
        n=lst/m;
        b=lst%m;
        swap(m,a);
    }
    return ans;
}
inline void solve()
{
    int n,m,a,b;
    cin>>n>>m>>a>>b;
    if(a==0)
    {
        cout<<min(n,b)<<'\n';
        return;
    }
    cout<<calc(n,m,a-1,b+m-1)-calc(n,m,a,b)<<'\n';
}
signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    int T;
    cin>>T;
    while(T--)solve();
}

:::