UVA 11768
题目原址
[https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2868]
(原来在vj做的,uva好卡)
题意
给你两个只有一位小数的浮点数的点,问在这两个点连成的线段上有几个整数点
题解
将这两个点的横纵坐标都乘10变为整数,特判线段斜率为0或无穷的情况,然后扩展gcd,找出一个整数解后,在原来的x1和x2之间找有多少个符合条件的解。
(原来我没将坐标换成整数来处理,结果超时了,不得不说double比long慢的不是一点点)
直接贴代码吧
#include<iostream>
#include<cmath>
#include<cstdio>
#include<float.h>
#include<algorithm>
using namespace std;
typedef long long ll;
const double eps=1e-8;
void exgcd(ll a,ll b,ll&g,ll&x,ll&y){
if(b==0){x=1;y=0;g=a;return;}
exgcd(b,a%b,g,y,x);
y-=a/b*x;
}
ll read(){
double x;
scanf("%lf",&x);
return (ll)(x*10+eps);
}
ll ceil(ll x){
return x/10+(x%10?1:0);
}
ll floor(ll x){
return x/10;
}
ll mabs(ll x){
return x<0?-x:x;
}
ll solve(ll x1,ll y1,ll x2,ll y2){
if(x1==x2)
if(x1%10)
return 0;
else{
if(y1>y2)swap(y1,y2);
return floor(y2)-ceil(y1)+1;
}
else if(y1==y2)
if(y1%10)
return 0;
else{
if(x1>x2)swap(x1,x2);
return floor(x2)-ceil(x1)+1;
}
else{
ll a=10*(y1-y2);
ll b=10*(x1-x2);
ll c=x2*y1-x1*y2;
ll g,x,y;
exgcd(a,b,g,x,y);
if(c%g)
return 0;
x*=c/g;
b=mabs(b/g);
if(x1>x2)swap(x1,x2);
// printf("x1=%lld,x2=%lld\n",x1,x2);
x1=ceil(x1);
x2=floor(x2);
// printf("x1=%lld,x2=%lld\n",x1,x2);
ll l=x+(x1-x)/b*b;
while(l<x1)l+=b;
ll r=x+(x2-x)/b*b;
while(r>x2)r-=b;
// printf("l=%lld,r=%lld,b=%lld\n",l,r,b);
return (r-l)/b+1;
}
}
int main(){
#ifdef LOCAL
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif // LOCAL
int T;cin>>T;
ll x1,y1,x2,y2;
while(T--){
x1=read();y1=read();x2=read();y2=read();
ll ans=solve(x1,y1,x2,y2);
printf("%lld\n",ans);
}
}