首页 > 代码库 > SGU 106. The equation 扩展欧几里德
SGU 106. The equation 扩展欧几里德
求解的个数
对应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 <cstdio> #include <cstring> #include <algorithm> 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 */
SGU 106. The equation 扩展欧几里德
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。