本文主要是介绍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));elseputs("0");}else if(!a && b){if(c%b == 0 && y1 <= c/b && y2 >= c/b)puts("1");elseputs("0");}else if(a && !b){if(c%a == 0 && x1 <= c/a && x2 >= c/a)puts("1");elseputs("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*kLL 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 扩展欧几里德的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!