求解的個數
對應ax+by=c 根據裴蜀定理c%gcd(a, b) == 0有解 假設d = gcd(a, b)
用擴展歐幾裡德求出方程aax+bb*y=cc 的解x0 y0
那麼原方程的一個解就是x0*c/d和y0*c/d
通解為
x = x0+i*b/d
y = y0+i*a/d
分別講x1 x2 帶入得到i 滿足最小的左區間 y1 y2一樣
#include#include #include using namespace std; typedef long long LL; //求整數x和y,使得ax+by=d, 且|x|+|y|最小。其中d=gcd(a,b) void gcd(LL a, LL b, LL& d, LL& x, LL& y) { if(!b) { d = a; x = 1; y = 0; } else { gcd(b, a%b, d, y, x); y -= x * (a/b); } } int main() { LL a, b, c, x1, x2, y1, y2; //scanf("%lld %lld %lld %lld %lld %lld %lld", &a, &b, &c, &x1, &x2, &y1, &y2); scanf("%I64d %I64d %I64d %I64d %I64d %I64d %I64d", &a, &b, &c, &x1, &x2, &y1, &y2); c = -c; if(a == 0 && b == 0) { if(c == 0) printf("%lld\n", (x2-x1+1)*(y2-y1+1)); else puts("0"); } else if(!a && b) { if(c%b == 0 && y1 <= c/b && y2 >= c/b) puts("1"); else puts("0"); } else if(a && !b) { if(c%a == 0 && x1 <= c/a && x2 >= c/a) puts("1"); else puts("0"); } else { LL x, y, d; gcd(a, b, d, x, y); if(c%d) puts("0"); else { //x = x0 + b/d*k; //y = x1 - a/d*k LL k1, k2, k3, k4, mi, ma; if(b/d > 0) { LL p = b/d; k1 = (x1-x*(c/d))/(b/d); k2 = (x2-x*(c/d))/(b/d); if(x*(c/d)+p*k1 < x1) k1++; if(x*(c/d)+p*k2 > x2) k2--; mi = k1; ma = k2; } else { LL p = -b/d; k1 = (-x2+x*(c/d))/(-b/d); k2 = (-x1+x*(c/d))/(-b/d); if(-x*(c/d)+p*k1 < -x2) k1++; if(-x*(c/d)+p*k2 > -x1) k2--; mi = k1; ma = k2; } if(-a/d > 0) { LL p = -a/d; k3 = (y1-y*(c/d))/(-a/d); k4 = (y2-y*(c/d))/(-a/d); if(y*(c/d)+p*k3 < y1) k3++; if(y*(c/d)+p*k4 > y2) k4--; mi = max(mi, k3); ma = min(ma, k4); } else { LL p = a/d; k3 = (-y2+y*(c/d))/(a/d); k4 = (-y1+y*(c/d))/(a/d); if(-y*(c/d)+p*k3 < -y2) k3++; if(-y*(c/d)+p*k4 > -y1) k4--; mi = max(mi, k3); ma = min(ma, k4); } //printf("%I64d %I64d\n", k3, k4); LL ans = ma-mi+1; if(ans < 0) ans = 0; printf("%lld\n", ans); } } return 0; } /* 1 1 -100000000 0 100000000 0 100000000 */