Lattice Point or Not

来源:互联网 发布:微信朋友圈 淘宝链接 编辑:程序博客网 时间:2024/06/07 12:54

扩展欧几里德(ExGCD)

Now a days a very common problem is:“The coordinate of two points in Cartesian coordinate system is (200, 300) and(4000, 5000). If these two points are connected we get a line segment. How manylattice points are there on this line segment.” You will have to do a similartask in this problem – the only difference is that the terminal coordinates canbe fractions.

Input

First line of the input file contains a positive integer N(N<=50000) that denotes how many lines of inputs follow. This line isfollowed by N lines each of which contains four floating-point numbers x1, y1,x2, y2 (0< |x 1 |, |y 1 |, |x 2 |, |y 2 |<=200000). These floating-point numbers has exactly one digit after thedecimal point.

Output

For each line of input exceptthe first line produce one line of output. This line contains an integer whichdenotes how many lattice points are there on the line segment that connects thetwo points (x1, y1) and (x2, y2).

SampleInput

 3 10.1 10.1 11.2 11.2 10.2 100.3 300.3 11.1 1.0 1.0 2.0 2.0

Output for Sample Input

102

Problemsetter: Shahriar Manzoor

Special Thanks: Derek Kisman

题意:求一条线段经过的整数点个数
思路:对于一般的求两个整点间线段上的格点个数,答案就是gcd(a,b)-1;而这道题目却是带有一位小数的点,这个就不能直接做了,要扩大成格点,而扩大的时候本来非格点也变成了格点,所以要求出ax+by=c的通解,然后转移到原来的区间去求格点个数。
在白板上的证明:
有点乱

代码如下:

#include <algorithm>#include <bitset>#include <cassert>#include <climits>#include <cmath>#include <cstdio>#include <cstdlib>#include <cstring>#include <deque>#include <iomanip>#include <iostream>#include <map>#include <numeric>#include <queue>#include <set>#include <stack>#include <string>#define INF 0x3f3f3f3fusing namespace std;typedef long long ll;ll exgcd(ll a,ll b,ll &x, ll &y){    ll d=a;    if(!b){x=1;y=0;}    else  {d=exgcd(b,a%b,y,x);y-=(a/b)*x;}    return d;}ll solve(double X1,double Y1,double X2,double Y2) {    ll x1=X1*10,x2=X2*10,y1=Y1*10,y2=Y2*10;    if (x1 == x2) {        if (x1 % 10)            return 0;        else {            y1=ceil(min(Y1, Y2));            y2=floor(max(Y1, Y2));            return max(y2-y1+1,(ll)0);        }    }    if (y1 == y2) {        if (y1 % 10)            return 0;        else {            x1 = ceil(min(X1,X2));            x2 = floor(max(X1,X2));            return max(x2-x1+1,(ll)0);        }    }    ll a=(y2-y1)*10,b=(x1-x2)*10,c=x1*y2-x2*y1;    ll x, y, d;    if(X1>X2)        swap(X1,X2);    x1=ceil(X1);    x2=floor(X2);    d=exgcd(a,b,x,y);    if (c%d)        return 0;    x*=c/d;b=abs(b/d);    //符合条件的第一个点    x-=(x-x1)/b*b;//回归到最靠近x1的解    if(x<x1)x+=b; //x1 x2可能不符合,需要先将x转移到x1 x2区间    if(x>x2)return 0;    return (x2-x)/b+1;}int main(){    int t;    cin>>t;    while(t--){        double x1,x2,y1,y2;        scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);        ll ans=solve(x1,y1,x2,y2);        printf("%lld\n",ans);    }    return 0;}

相关证明:ExGCD证明,本题算法原理

0 0