SGU 106 The equation(扩展欧几里得)
来源:互联网 发布:ubuntu kylin qq下载 编辑:程序博客网 时间:2024/04/29 15:25
Description
求方程ax+by+c=0的满足x1<=x<=x2且y1<=y<=y2的解的个数
Input
七个整数a,b,c,x1,x2,y1,y2,所有数的绝对值不超过10^8
Output
输出解的个数
Sample Input
1 1 -3
0 4
0 4
Sample Output
4
Solution
特殊情况的处理详见代码,现只考虑最朴素的情况
将方程转化为ax+by=c的形式,其中a,b>0且gcd(a,b)=1
由扩展欧几里得可以得到一组满足ax+by=1的(x,y),令x=cx,y=cy则得到一组满足ax+by=c的解(x,y),那么(x+tb,y-ta)也是方程的解,每个t代表一个解
由x1<=x+tb<=x2及y1<=y-ta<=y2得t的取值范围为(l,r)
其中l=max((x1-x)/b,(y-y2)/a),r=min((x2-x)/b,(y-y1)/a)
那么解的个数即为max(r-l+1,0)
Code
#include<cstdio>#include<iostream>#include<algorithm>#include<cmath>using namespace std;typedef long long ll;ll gcd(ll a,ll b){ if(!b)return a; return gcd(b,a%b);}ll extend_gcd(ll a,ll b,ll &x,ll &y){ ll d=a; if(b!=0) d=extend_gcd(b,a%b,y,x),y-=(a/b)*x; else x=1,y=0; return d;}int main(){ ll a,b,c,x1,y1,x2,y2; while(~scanf("%lld%lld%lld%lld%lld%lld%lld",&a,&b,&c,&x1,&x2,&y1,&y2)) { ll ans; c=-c; if(c<0)c=-c,a=-a,b=-b; if(a<0)a=-a,swap(x1,x2),x1=-x1,x2=-x2; if(b<0)b=-b,swap(y1,y2),y1=-y1,y2=-y2; if(x1>x2||y1>y2)ans=0; else if(a==0&&b==0) { if(c==0)ans=1ll*(x2-x1+1)*(y2-y1+1); else ans=0; } else if(a==0) { if(c%b==0&&c/b>=y1&&c/b<=y2)ans=x2-x1+1; else ans=0; } else if(b==0) { if(c%a==0&&c/a>=x1&&c/a<=x2)ans=y2-y1+1; else ans=0; } else { ll g=gcd(a,b); if(c%g!=0)ans=0; else { a/=g,b/=g,c/=g; ll x,y; extend_gcd(a,b,x,y); x*=c,y*=c; ll l1=ceil(1.0*(x1-x)/b),l2=ceil(1.0*(y-y2)/a); ll r1=floor(1.0*(x2-x)/b),r2=floor(1.0*(y-y1)/a); ll r=min(r1,r2),l=max(l1,l2); ans=l<=r?r-l+1:0; } } printf("%lld\n",ans); }}
0 0
- SGU - 106 - The equation (扩展欧几里得)
- SGU 106 The equation(扩展欧几里得)
- SGU 106 The equation 【扩展欧几里得算法】
- SGU 106 The Equation 扩展欧几里得应用
- SGU 106 The equation ----扩展欧几里得
- SGU 106 The equation【扩展欧几里得】
- SGU 106 The equation(扩展欧几里德)
- SGU 106 The equation(拓展欧几里得)
- The equation----扩展欧几里得
- SGU 106 The equation (扩展GCD/多特判)
- SGU 106 The equation(扩展欧几里德)
- sgu 106 The equation
- SGU 106 The equation
- sgu 106 The equation
- SGU 106 The equation
- SGU 106 The equation
- SGU 106 The equation
- SGU 106 The equation
- (一)IBM Sterling OMS 环境构建之JDK
- Baby-step giant-step 解高次同余方程a^x=b(mod n) 模版
- Nginx+Memcached+Tomcat集群配置实践
- MAC && PIN
- Android Mediacodec硬解H264并显示
- SGU 106 The equation(扩展欧几里得)
- matlab中clear,clc,clf,hold作用
- [从头学数学] 第176节 概率
- Angular JS1学习笔记之一指令
- TrimTest.exe SrcFilePath targetFilePath
- Java reflect--动态执行Method-代码
- 数据库查询下一条
- Android Pingpong漏洞解析
- RTP协议分析