博客
关于我
LightOJ - 1077 How Many Points
阅读量:810 次
发布时间:2023-01-31

本文共 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]

  • 编程实现

    • 包含必要的头文件。
    • 定义长长整数类型。
    • 定义gcd函数,使用欧几里得算法。
    • 读取输入,处理每个测试用例,计算并输出结果。
  • 代码示例:

    #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; 定义长长整数类型,便于处理大数。
    • gcd函数:使用递归实现欧几里得算法计算最大公约数。
    • 主函数
      • 读取测试用例数目T。
      • 对于每个测试用例,读取四个坐标值。
      • 计算坐标差的绝对值。
      • 使用gcd函数计算最大公约数。
      • 输出结果为gcd值加1。

    这个程序能够高效地解决问题,适用于多个测试用例,并且代码结构清晰,易于理解和维护。

    转载地址:http://dzwfk.baihongyu.com/

    你可能感兴趣的文章
    Prometheus+Grafana构建智能化Kubernetes监控系统实战
    查看>>
    Prometheus+SpringBoot应用监控全过程详解
    查看>>
    Prometheus+SpringBoot应用监控全过程详解
    查看>>
    prometheus安装
    查看>>
    Prometheus实战教程:监控Kafka消息
    查看>>
    Prometheus实战教程:监控mysql数据库
    查看>>
    Prometheus实战教程:监控Nginx状态
    查看>>
    prometheus常用exporter下载地址大全
    查看>>
    Prometheus快速搭建与监控Linux系统实战
    查看>>
    prometheus报警与恢复告警的格式
    查看>>
    Pytorch中安装 torch_geometric 详细图文操作(全)
    查看>>
    prometheus监控docker容器实战
    查看>>
    Prometheus监控k8s集群使用邮箱和微信告警!
    查看>>
    Prometheus监控mysq数据库实战
    查看>>
    prometheus监控nginx实战
    查看>>
    Prometheus监控redis数据库实战
    查看>>
    Prometheus监控教程:使用Grafana展示主机基本信息
    查看>>
    pytorch中如何使用预训练词向量
    查看>>
    Prometheus监控教程:使用PromQL查询监控数据(上篇)
    查看>>
    Prometheus监控教程:使用PromQL查询监控数据(下篇)
    查看>>