博客
关于我
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 on Kubernetes部署
    查看>>
    prometheus + grafana进行服务器资源监控
    查看>>
    Prometheus Alertmanager 告警配置详解
    查看>>
    Prometheus Grafana 展示平台
    查看>>
    Prometheus pushgateway使用详解
    查看>>
    Prometheus 云原生 - Prometheus 数据模型、Metrics 指标类型、Exporter 相关
    查看>>
    Prometheus 云原生 - 基于 file_sd、http_sd 实现 Service Discovery
    查看>>
    Prometheus 云原生 - 微服务监控报警系统 (Promethus、Grafana、Node_Exporter)部署、简单使用
    查看>>
    Prometheus 云原生 - 监控 Linux、MySQL、Redis、RabbitMQ、Docker、SpringBoot 3.x
    查看>>
    Prometheus 介绍
    查看>>
    Prometheus 安全配置详解
    查看>>
    prometheus 安装node_exporter, node_exporter 安装最新版 普罗米修思安装监控服务器client
    查看>>
    Prometheus 安装部署实战
    查看>>
    prometheus 持久化存储方案
    查看>>
    Prometheus 监控系统企业级实战
    查看>>
    Prometheus 监控系统简介
    查看>>
    Prometheus 配置详解
    查看>>
    Prometheus 采集器使用详解
    查看>>
    Prometheus 黑盒监控实战
    查看>>
    prometheus+alertmanager+grafana监控部署教程
    查看>>