博客
关于我
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/

    你可能感兴趣的文章
    Processing通过编程实现艺术设计_实现艺术和现实的交互---数据设计分析002
    查看>>
    ProcessOnLoading
    查看>>
    SpringBoot中集成screw(螺丝钉)实现数据库表结构文档生成
    查看>>
    PROFINET 模拟器使用教程
    查看>>
    Program type already present: android.support.v4.widget.EdgeEffectCompat
    查看>>
    PyTorch中文版官方教程来啦(附下载)
    查看>>
    Progress Kemp LoadMaster 远程命令执行漏洞复现(CVE-2024-1212)
    查看>>
    Project configuration is not up-to-date with pom.xml. Run Maven->Update Project
    查看>>
    Project Euler 15 Lattice paths
    查看>>
    Project Euler 48 Self powers( 大数求余 )
    查看>>
    Project Euler Problem 12: Highly divisible triangular number
    查看>>
    ProjectEuler 2
    查看>>
    projection介绍及EPSG:4326和EPSG:3857的投射转换
    查看>>
    project打开文件时,显示无法识别此文件格式?
    查看>>
    Prometheus + Grafana on Kubernetes部署
    查看>>
    prometheus + grafana进行服务器资源监控
    查看>>
    Prometheus Alertmanager 告警配置详解
    查看>>
    Prometheus Grafana 展示平台
    查看>>
    Prometheus pushgateway使用详解
    查看>>
    Prometheus 云原生 - Prometheus 数据模型、Metrics 指标类型、Exporter 相关
    查看>>