codevs1213 解的个数
题目描述 Description
已知整数x,y满足如下面的条件:
ax+by+c = 0
p<=x<=q
r<=y<=s
求满足这些条件的x,y的个数。
输入描述 Input Description
第一行有一个整数n(n<=10),表示有n个任务。n<=10
以下有n行,每行有7个整数,分别为:a,b,c,p,q,r,s。均不超过108。
输出描述 Output Description
共n行,第i行是第i个任务的解的个数。
样例输入 Sample Input
2
2 3 -7 0 10 0 10
1 1 1 -10 10 -9 9
样例输出 Sample Output
1
19
#include<iostream> #include<cstdio> #include<algorithm> #define ll long long using namespace std; ll x,y,a,b,c,g,p,q,r,s; ll exgcd(ll a,ll b,ll &x,ll &y){ if(b == 0){ x = 1; y = 0; return a; } ll ans = exgcd(b,a%b,x,y); ll t = x; x = y; y = t - (a/b) * y; return ans; } ll gcd(ll a,ll b){ return b == 0 ? a : gcd(b,a%b); } int main(){ int n; cin>>n; for(int i = 1;i <= n;i++){ cin>>a>>b>>c>>p>>q>>r>>s; c = -c; if(a == 0 && b == 0 && c!= 0){ cout<<0<<endl; continue; } if(q < p || s < r){ cout<<0<<endl; continue; } if(a == 0 && b== 0 && c==0){ cout<<(q-p+1)*(s-r+1)<<endl; continue; } g = exgcd(a,b,x,y); x *= c/g; y *= c/g; if(x*a + y*b != c){ cout<<0<<endl; continue; } ll plusx = b / g,plusy = a / g,dx,dy; ll acc = 0; bool fu; if(plusx < 0) fu = true; else fu = false; while(x < p){ if(plusx == 0) break; if(!fu) x+=plusx,y-=plusy; else x-=plusx,y+=plusy; } while(x > q){ if(plusx == 0) break; if(!fu) x-= plusx,y+=plusy; else x+=plusx,y-=plusy; } if(x >= p && x <= q && y >= r && y <= s)acc++; dx = x; dy = y; while(dx >= p){ if(plusx == 0) break; if(!fu){ dx -= plusx; dy += plusy; }else{ dx += plusx; dy -= plusy; } if(dx >= p && dx <= q && dy >= r && dy <= s) acc++; } dx = x; dy = y; while(dx <= q){ if(plusx == 0) break; if(!fu){ dx += plusx; dy -= plusy; }else{ dx -= plusx; dy += plusy; } if(dx >= p && dx <= q && dy >= r && dy <= s) acc++; } cout<<acc<<endl; } return 0; }