The equation SGU - 106 (扩展欧几里得公式)
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
题意:
给出a*x+b*y+c=0的a,b,c的值以及x,y的范围[x1,x2],[y1,y2]。求范围内满足该式的
(x,y)有序对的个数。
参考的这位大神的博客,讲的特别清楚。(http://www.cnblogs.com/Rinyo/archive/2012/11/25/2787419.html)
思路:根据扩展欧几里得公式可以求出一个特解(x0,y0)。
则通解为(x0+k*(b/g),y0-k*(a/g)) ps:(g=gcd(a,b))
现在只要根据给出的范围找出k的上限和下限,然后求差就行了。
这里注意因为通解
y1<=(y=y0-k*(a/g))<=y2
-y2<=k*(a/g)<=-y1
(-y2)/(a/g),(-y1)/(a/g)可能为小数,所以我们要解决k的取值问题。
假如2.5<=k<=5.5,显然k要取3,4,5;
假如-6.5<=k<=-4.5,显然k取-6,-5,-4。
即下限取较大值,上限取较小值。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define LL long long
using namespace std;
LL ex_gcd(LL a,LL b,LL& x,LL& y)
{
if(b==0)
{
x=1,y=0;
return a;
}
int ans=ex_gcd(b,a%b,x,y);
int tmp=x;
x=y;
y=tmp-a/b*y;
return ans;
}
int gcd(int a,int b)
{
if(b==0) return a;
else return gcd(b,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);
c=-c;
//这里使a,b,c的值为正的同时改变区间,方便以后计算k的上下限
if(c<0)
{
a=-a,b=-b,c=-c;
}
if(a<0)
{
a=-a;
LL tmp=x1;
x1=-x2;
x2=-tmp;
}
if(b<0)
{
b=-b;
LL tmp=y1;
y1=-y2;
y2=-tmp;
}
//特判,因为时间为250ms
if(a==0||b==0)
{
if(a==0&&b==0)
{
if(c==0)
cout<<(x2-x1+1)*(y2-y1+1)<<endl;
else
cout<<0<<endl;
return 0;
}
else if(a==0)
{
if(c%b==0&&c/b>=y1&&c/b<=y2)
cout<<x2-x1+1<<endl;
else
cout<<0<<endl;
return 0;
}
else
{
if(c%a==0&&c/a>=x1&&c/a<=x2)
cout<<y2-y1+1<<endl;
else cout<<0<<endl;
return 0;
}
}
LL x,y;
LL g=ex_gcd(a,b,x,y);
if(c%g!=0)
{
cout<<0<<endl;
return 0;
}
a/=g,b/=g,c/=g;
x*=c;
y*=c;
LL k1=max(ceil((x1-x)*1.0/b),ceil((y-y2)*1.0/a));
//ceil()函数,向上取整
LL k2=min(floor((x2-x)*1.0/b),floor((y-y1)*1.0/a));
//floor()函数,向下取整
if(k2>=k1)
cout<<k2-k1+1<<endl;
else
cout<<0<<endl;
return 0;
}
注意用long long,不然会WA。对于long long过 与 int不过的问题,一直很玄学。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步