题解:AT_abc443_g [ABC443G] Another Mod of Linear Problem
模板欸。
先转换为
考虑利用
将
注意到左式减右式一定
这是经典的类欧的形式,直接做就好了,注意特判
:::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();
}
:::