本文共 1113 字,大约阅读时间需要 3 分钟。
给定两个格点,求它们之间线段上的格点数目。这个问题可以通过计算两个点坐标差的最大公约数(gcd)来解决。具体来说,线段上的格点数目等于gcd(abs(x1-x2), abs(y1-y2)) + 1。
问题分析:给定两个点 (x1, y1) 和 (x2, y2),我们需要计算连接它们的线段上包含多少个格点。根据贝祖定理,两个点之间的线段上格点数目为它们坐标差的gcd加1。
公式应用:计算两点坐标差的绝对值的gcd,然后加1即可得到结果。公式为:[\text{格点数目} = \text{gcd}(|x1 - x2|, |y1 - y2|) + 1]
编程实现:
#include#include #include #include using namespace std;typedef long long LL;LL gcd(LL a, LL b) { return b == 0 ? a : gcd(b, a % b);}int main() { int T; scanf("%d", &T); for (int t = 1; t <= T; t++) { LL x1, y1, x2, y2; scanf("%lld%lld%lld%lld", &x1, &y1, &x2, &y2); LL dx = abs(x1 - x2); LL dy = abs(y1 - y2); LL g = gcd(dx, dy); printf("Case %d: %lld\n", t, g + 1); } return 0;}
<stdio.h>、<string.h>、<iostream> 和 <algorithm>,用于基础输入输出和算法支持。typedef long long LL; 定义长长整数类型,便于处理大数。这个程序能够高效地解决问题,适用于多个测试用例,并且代码结构清晰,易于理解和维护。
转载地址:http://dzwfk.baihongyu.com/