题目传送:106. The equation
106. The equation
time limit per test: 0.25 sec.
memory limit per test: 4096 KB
There is an equation ax + by + c = 0. Given a,b,c,x1,x2,y1,y2 you must determine, how many integer roots of this equation are satisfy to the following conditions : x1<=x<=x2, y1<=y<=y2. Integer root of this equation is a pair of integer numbers (x,y).
Input
Input contains integer numbers a,b,c,x1,x2,y1,y2 delimited by spaces and line breaks. All numbers are not greater than 108 by absolute value.
Output
Write answer to the output.
Sample Input
1 1 -3
0 4
0 4
Sample Output
4
简单的扩展欧几里得,,看了好久,,参考的该博客(点这里)
AC代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <deque>
#include <cctype>
#define LL long long
#define INF 0x7fffffff
#define DB double
using namespace std;
LL a, b, c;
LL xx, yy;
LL x1, x2;
LL yy1, y2;
void exgcd(LL a, LL b, LL &x, LL &y) {
if(!b) { x = 1; y = 0; }
else {
exgcd(b, a % b, y, x);
y -= x * (a / b);
}
}
LL gcd(LL a, LL b) {
return b == 0 ? a : gcd(b, a % b);
}
int main() {
cin >> a >> b >> c >> x1 >> x2 >> yy1 >> y2;
c = -c;
if(c < 0) { a = -a; b = -b; c = -c; }
if(a < 0) { a = -a; LL t = x1; x1 = -x2; x2 = -t; }
if(b < 0) { b = -b; LL t = yy1; yy1 = -y2; y2 = -t; }
if(a == 0 && b == 0) {
if(c == 0) {
cout << (x2 - x1 + 1) * (y2 - yy1 + 1) << endl;
return 0;
}
cout << "0" << endl;
return 0;
}
if(a == 0) {
if(c % b == 0 && c / b <= y2 && c / b >= yy1) {
cout << x2 - x1 + 1 << endl; return 0;
}
cout << "0" << endl;
return 0;
}
if(b == 0) {
if(c % a == 0 && c / a <= x2 && c / a >= x1) {
cout << y2 - yy1 + 1 << endl; return 0;
}
cout << "0" << endl;
return 0;
}
LL d = gcd(a, b);
if(c % d != 0) {
cout << "0" << endl; return 0;
}
a /= d; b /= d; c /= d;
exgcd(a, b, xx, yy);
xx *= c; yy *= c;
//求出k的取值范围
LL down1 = floor( ((DB)x2 - xx) / b), down2 = floor( ((DB)yy - yy1)/a );
LL r = min(down1, down2);
LL up1 = ceil((((DB)x1-xx)/b)), up2 = ceil((((DB)yy-y2)/a));
LL l = max(up1, up2);
if(r < l) cout << "0" << endl;
else cout << r - l + 1 << endl;
return 0;
}