LightOJ 1306

本题是极其裸的EXGCD AX+BY+C=0 给你a b c 和x与y的区间范围,问你整数解有几组 作为EXGCD入门,题目比较简单 主要需要考虑区间范围的向上、向下取整,及正负符号的问题 *问题是这正负号判断考虑让我WA无数次* **我好菜阿** > 补充:关于使用扩展欧几里德算法解决不定方程的办法 >对于不定整数方程pa+qb=c,若 c mod Gcd(p, q)=0,则该方程存在整数解,否则不存在整数解。 >上面已经列出找一个整数解的方法,在找到p * a+q * b = Gcd(p, q)的一组解p0,q0后,p * a+q * b = Gcd(p, q)的其他整数解满足: >p = p0 + b/Gcd(p, q) * t >q = q0 – a/Gcd(p, q) * t(其中t为任意整数) >至于pa+qb=c的整数解,只需将p * a+q * b = Gcd(p, q)的每个解乘上 c/Gcd(p, q) 即可 >——摘自他人博客
/** @Date    : 2016-10-21-15.24
* @Author : Lweleth (SoungEarlf@gmail.com)
* @Link :
* @Version : $
*/
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <algorithm>
#include <utility>
#include <vector>
#include <map>
#include <set>
#include <math.h>
#include <string>
#include <stack>
#include <queue>
#define LL long long
#define MMF(x) memset((x),0,sizeof(x))
#define MMI(x) memset((x), INF, sizeof(x))
using namespace std;

const int INF = 0x3f3f3f3f;
const int N = 1e5+2000;


LL exgcd(LL a, LL b, LL &x, LL &y)
{
LL d = a;
if(b == 0)
{
x = 1;
y = 0;
}
else
{
d = exgcd(b, a % b, y, x);
y -= (a / b)*x;
}
return d;
}

int main()
{
int T;
int cnt = 0;
cin >> T;
while(T--)
{
LL a, b, c, x1, x2, y1, y2;
scanf("%lld%lld%lld", &a, &b, &c);
scanf("%lld%lld%lld%lld",&x1, &x2, &y1, &y2);
c = -c;
if(a < 0)
{
a = -a;
swap(x1, x2);
x1 = -x1;
x2 = -x2;
}
if(b < 0)
{
b = -b;
swap(y1, y2);
y1 = -y1;
y2 = -y2;
}
printf("Case %d: ", ++cnt);
LL x0 = 0 , y0 = 0;


LL g = exgcd(a, b, x0, y0);
if(g!=0 && c % g != 0)
{
printf("0 ");
continue;
}
if(a == 0 && b == 0)
{
if(!c)
printf("%lld ", (x2 - x1 + 1) * (y2 - y1 + 1));
else printf("0 ");
continue;

}
if(a == 0)
{
if(c / b >= y1 && c/b <= y2)
printf("%lld ", x2 - x1 + 1);
else printf("0 ");
continue;
}
if(b == 0)
{
if(c / a >= x1 && c / a <= x2)
printf("%lld ", y2 - y1 + 1);
else printf("0 ");
continue;

}

x0 = x0 * c / g;
y0 = y0 * c / g;
a /= g;
b /= g;
LL l = ceil((double)(x1 - x0)/(double)(b));
LL r = floor((double)(x2 - x0)/(double)(b));
LL w = ceil((double)(y0 - y2)/(double)(a));
LL e = floor((double)(y0 - y1)/(double)(a));
LL q = max(l, w);
LL p = min(r, e);
if(p < q)
printf("0 ");
else printf("%lld ", p - q + 1);
}
return 0;
}
原文地址:https://www.cnblogs.com/Yumesenya/p/6008263.html