博客
关于我
HDU 2669 Romantic(扩展欧几里得算法)
阅读量:719 次
发布时间:2019-03-21

本文共 1394 字,大约阅读时间需要 4 分钟。

为了解决这个问题,我们需要找到满足方程 ax + by = 1 的整数解,其中 x 是非负的,并且尽可能小。只有当 a 和 b 互质时,这个方程才有解。我们可以通过扩展欧几里得算法来找到一组解,并对其进行调整以满足要求。

方法思路

  • 检查互质性:首先检查 a 和 b 是否互质,即它们的最大公约数是否为 1。只有当它们互质时,方程才有解。
  • 扩展欧几里得算法:使用扩展欧几里得算法找到一个初始解 (x0, y0)。这个解可能会有负数的 x。
  • 调整解:将初始解进行调整,使得 x 变为正数。通过调整,我们可以找到所有可能的解中的 x 最小的非负的解。
  • 解决代码

    #include 
    #pragma warning(disable:4996)int a, b, x, y;int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b);}int extgcd(int a, int b, int x, int y) { int d = a; if (b != 0) { d = extgcd(b, a % b, x, y); y -= (a / b) * x; } else { x = 1; y = 0; } return d;}int main() { while (scanf("%d %d", &a, &b) != EOF) { if (extgcd(a, b, x, y) > 1) { puts("sorry"); continue; } if (y < 0) { y = -y; a = -a; } if (x < 0) { x = -x; b = -b; } if (extgcd(a, b, x, y, 1) != 1) { puts("sorry"); continue; } while (x >= 0) { x -= b; y += a; } while (x < 0) { x += b; y -= a; } printf("%d %d\n", x, y); } return 0;}

    代码解释

  • 输入处理:使用 scanf 读取输入,直到 EOF。
  • 检查互质性:通过扩展欧几里得算法检查 a 和 b 的最大公约数,如果大于 1,则输出 "sorry"。
  • 初始解调整:对于可能的负数解,通过调整 x 和 y 以确保它们是正整数。
  • 调整解:利用扩展欧几里得算法的结果,进一步调整 x 和 y,使得 x 为最小的非负解。
  • 输出结果:打印满足条件的 x 和 y 的值。
  • 通过这种方法,我们能够高效地找到满足条件的解,并确保输出的 x 是最小的非负整数。

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

    你可能感兴趣的文章
    npm发布自己的组件UI包(详细步骤,图文并茂)
    查看>>
    npm和package.json那些不为常人所知的小秘密
    查看>>
    npm和yarn清理缓存命令
    查看>>
    npm和yarn的使用对比
    查看>>
    npm如何清空缓存并重新打包?
    查看>>
    npm学习(十一)之package-lock.json
    查看>>
    npm安装 出现 npm ERR! code ETIMEDOUT npm ERR! syscall connect npm ERR! errno ETIMEDOUT npm ERR! 解决方法
    查看>>
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>