sgu106 The Equation 扩展欧几里德

题意:求ax+by+c=0,x1<=x<=x2,y1<=y<=y2的整数解个数。

思路:先特判下 a=0且b=0、a=0且b!=0、b=0且a!=0的情况。对于一般情况,首先求出ax+by=gcd(a,b)=g的解,c=-c,那么如果

c%g=0,说明有整数解。不妨设解为x0,y0,那么此解也是a'x+b'y=1的解,其中a'=a/g,b'=b/g。那么我们可以发现x=x0+kb',y=y0-ka'为方

程的通解。若要满足x1<=x<=x2,y1<=y<=y2,则x1-x0<=kb'<=x2-x0,y0-y2<=ka'<=y0-y1,分别求出lx,rx,ly,ry,则答案为:

min(rx,ry)-max(lx,ly)+1。要注意一个wa点,程序中a/b是向零取整的,设b>0,所以如果a<0的处理与a>0是不同的,一直wa on test 3

是这个原因 = = ,详见代码: 

// file name: sgu106.cpp //
// author: kereo //
// create time:  2014年09月20日 星期六 22时26分08秒 //
//***********************************//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<set>
#include<map>
#include<vector>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
typedef long long ll;
const int MAXN=100000+100;
const int inf=0x3fffffff;
const int mod=1000000000+7;
#define L(x) (x<<1)
#define R(x) (x<<1|1)
ll a,b,c,x1,x2,y1,y2;
ll ex_gcd(ll a,ll b,ll &x,ll &y){
	if(!b){
		x=1; y=0;
		return a;
	}
	else{
		ll res=ex_gcd(b,a%b,y,x); y-=a/b*x;
		return res;
	}
}
ll upper(ll a,ll b){
	if (a<=0)
		return a/b;
    return (a-1)/b + 1;
}
ll lower(ll a,ll b){
	if (a>=0)
		return a/b;
    return (a+1)/b - 1;
 }
int main()
{
	while(~scanf("%lld%lld%lld%lld%lld%lld%lld",&a,&b,&c,&x1,&x2,&y1,&y2)){
		ll x,y;
		c=-c;
		if(a == 0 && b == 0){
			if(c!=0)
				printf("0\n");
			else
				printf("%lld\n",(x2-x1+1)*(y2-y1+1));
			continue;
		}
		if(a == 0 && b!=0){
			if(c%b == 0 && c/b>=y1 && c/b<=y2)
				printf("1\n");
			else
				printf("0\n");
			continue;
		}
		if(b == 0 && a!=0){
			if(c%a == 0 && c/a>=x1 && c/a<=x2)
				printf("1\n");
			else
				printf("0\n");
			continue;
		}
		ll g=ex_gcd(a,b,x,y);
		if(c%g){
			printf("0\n");
			continue;
		}
		x*=c/g; y*=c/g;
		a/=g; b/=g;
		ll lx,rx;
		ll L=x1-x,R=x2-x;
		if(b<0){
			b=-b; L=-L; R=-R; swap(L,R);
		}	
		lx=upper(L,b); rx=lower(R,b);
		ll ly,ry;
		L=y-y2; R=y-y1;
		if(a<0){
			a=-a; L=-L; R=-R; swap(L,R);
		}
		ly=upper(L,a); ry=lower(R,a);
		ll l,r;
		l=max(ly,lx); r=min(ry,rx);
		ll ans=r-l+1;
		if(ans<0) ans=0;
		printf("%lld\n",ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值