UVA - 11768 Lattice Point or Not (拓展gcd)

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< |x1|, |y1|, |x2|, |y2|<=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                              Output for Sample Input

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

1

0

2

 


Problemsetter: Shahriar Manzoor

Special Thanks: Derek Kisman

题意:求一条线段经过的整数点个数

思路:先将线段转换成直线方程,那么我们就可以用拓展gcd来求解了,然后就是找这两个点范围内的解就是了

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
typedef long long ll;
using namespace std;

void gcd(ll a, ll b, ll &d, ll &x, ll &y) {  
	if (!b) { d = a; x = 1; y = 0; }  
	else { gcd(b, a%b, d, y, x); y -= x*(a/b); }  
}  

ll sovle(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;
		y1 = ceil(min(Y1, Y2));
		y2 = floor(max(Y1, Y2));
		return max(y2-y1+1, 0ll);
	}
	if (y1 == y2) {
		if (y1 % 10)
			return 0;
		if (X2 < X1)
			swap(X2, X1);
		x1 = ceil(X1), x2 = floor(X2);		
		return max(x2-x1+1, 0ll);
	}
	ll a = (y2-y1)*10, b = (x1-x2)*10, c = x1*y2-x2*y1;
	ll x, y, d, k1 = 0;
	if (X2 < X1)
		swap(X2, X1);
	x1 = ceil(X1), x2 = floor(X2);
	if (x1 > x2)
		return 0;
	gcd(a, b, d, x, y);
	if (c % d != 0)
		return 0;
	a /= d, b /= d;
	x *= (c/d), y *= (c/d);
	if (b < 0)
		b = -b;
	x = x-(x-x1)/b*b;
	x -= b;
	while (x < x1)
		x += b;
	k1 = 0;
	while (x + k1 * b <= x2)
		k1++;
	return k1;
}

int main() {
	double x1, y1, x2, y2;
	int t;
	scanf("%d", &t);
	while (t--) {
		scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
		ll ans = sovle(x1, y1, x2, y2);
		printf("%lld\n", ans);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值