It's a Mod, Mod, Mod, Mod World (类欧几里得模板题
https://vjudge.net/contest/317000#problem/F
#include <iostream> #include <cstdio> #include <queue> #include <algorithm> #include <cmath> #include <cstring> #define inf 2147483647 #define P 998244353 #define p(a) putchar(a) #define For(i,a,b) for(long long i=a;i<=b;++i) using namespace std; long long T; long long n,a,b,c; struct data{ long long f,g,h; data calc(long long n,long long a,long long b,long long c){ long long ac = a / c, bc = b / c, m = (a * n + b) / c, n1 = n + 1, n21 = n * 2 + 1; data d; if (a == 0) { d.f = bc * n1; d.g = bc * n * n1 /2; d.h = bc * bc * n1; return d; } if (a >= c || b >= c){ d.f = n * n1 /2 * ac + bc * n1; d.g = ac * n * n1 * n21 /6 + bc * n * n1 / 2; d.h = ac * ac * n * n1 * n21 /6 + bc * bc * n1 + ac * bc * n * n1; data e = calc(n, a % c, b % c, c); d.h += e.h + 2 * bc * e.f + 2 * ac * e.g; d.g += e.g, d.f += e.f; return d; } data e = calc(m - 1, c, c - b - 1, a); d.f = n * m - e.f, d.f = d.f; d.g = m * n * n1 - e.h - e.f, d.g = d.g /2; d.h = n * m * (m + 1) - 2 * e.g - 2 * e.f - d.f; return d; } }ans1,ans2; void in(long long &x){ long long y=1;char c=getchar();x=0; while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();} while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=getchar();} x*=y; } void o(long long x){ if(x<0){p('-');x=-x;} if(x>9)o(x/10); p(x%10+'0'); } signed main(){ in(T); while(T--){ in(a);in(c);in(n); ans1=ans1.calc(n,a,0,1); ans2=ans2.calc(n,a,0,c); o(ans1.f-c*ans2.f);p('\n'); } return 0; }