SGU - 106 - The equation (扩展欧几里得)

该博客介绍了如何使用扩展欧几里得算法解决ax + by + c = 0的整数解问题。在给定的x和y的范围内寻找满足条件的解,并给出了输入输出格式及样例。
摘要由CSDN通过智能技术生成


题目传送: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;
}









  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值