程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> SGU 106. The equation 擴展歐幾裡德

SGU 106. The equation 擴展歐幾裡德

編輯:C++入門知識

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 
#include 
#include 
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
*/


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved