题目描述:
106. The equation
time limit per test: 0.5 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 WA无数次啊,我好水啊。。。。 先扩展欧几里德解出基本解,然后做判断。 这里各种错。(一定要思考清楚再敲啊) 基本思路就是求得一个符合条件的区间,然后合并他们。 记得要对a,b做等0的讨论。 附上好不容易AC的代码:#include<iostream> #include<cstring> #include<cstdio> #include<set> #include<algorithm> #include<vector> #include<cstdlib> #define inf 0xfffffff #define CLR(a,b) memset((a),(b),sizeof((a))) #define int long long using namespace std; int const nMax = 100010; typedef int LL; typedef pair<LL,LL> pij; int extgcd(int a,int b,int &x,int &y){ if(b==0){ x=1,y=0; return a; } int d=extgcd(b,a%b,x,y); int t=y; y=x-a/b*y; x=t; return d; } int x1,x2,y1,y2; int mini,maxi; int up(int R,int d){ if(R>=0) return R/d; return (R+1)/d-1; } int lo(int L,int d){ if(L<=0) return L/d; return (L-1)/d+1; } void relax(int L,int R,int d){ if(d<0)L=-L,R=-R,d=-d,swap(R,L); mini=max(mini,lo(L,d)); maxi=min(maxi,up(R,d)); } int equ(int a,int b,int n){ int x,y; int d=extgcd(a,b,x,y); if(n%d)return 0; x=x*(n/d); y=y*(n/d); mini=-inf,maxi=inf; relax(x1-x,x2-x,b/d); relax(y1-y,y2-y,-a/d); int ans=maxi-mini+1; if(ans<0)ans=0; return ans; } int a,b,c; main() { // cout<<-3/2<<endl; cin>>a>>b>>c>>x1>>x2>>y1>>y2; int ans=0; if(a==0&&b){ if(c%b!=0){ cout<<0<<endl; }else{ int y=c/b; y=-y; if(y>=y1&&y<=y2)cout<<1<<endl; else cout<<0<<endl; } }else if(a&&b==0){ if(c%a!=0){ cout<<0<<endl; }else { int x=c/a; x=-x; if(x>=x1&&x<=x2)cout<<1<<endl; else cout<<0<<endl; } }else if(a==0&&b==0){ if(c==0){ cout<<(x2-x1+1)*(y2-y1+1)<<endl; }else cout<<0<<endl; }else{ ans=equ(a,b,-c); if(ans<0)ans=0; cout<<ans<<endl; } return 0; }