The Balance POJ - 2142 (扩展欧几里得定理)

问题虫洞:The Balance POJ - 2142

 

黑洞内窥:

多组输入,每组输入A、B、C三个数字;

表示 Ax = By + C 或者 Ax = By + C, 求最小的min(x+y);

 

思维光年:

变型一下上面的两个式子:

Ax - By = C

Ax - By = C

问题改为:求着两组解的一个最小正整数解x,求此时的(x+y)的最小值;

 

ACcode:

//#include<bits/stdc++.h>
#include  <stdio.h>
#include <iostream>
#include<algorithm>
#include <stdlib.h>
#include  <cstring>
#include <string.h>
#include   <string>
#include   <math.h>
using namespace std;
typedef long long ll;
#define MAXN 1000005
#define INF 0x3f3f3f3f//将近ll类型最大数的一半,而且乘2不会爆ll
const ll mod = 1000000007;

ll exgcd(int a, int b, int &x, int &y)
{
    if(b == 0)
    {
        x = 1;
        y = 0;
        return a;
    }
    int gcd = exgcd(b, a%b, x, y);
    int t = x;
    x = y;
    y = t - a/b*y;
    return gcd;
}

int main()
{
    int a, b, c;
    while(cin >> a >> b >> c && a+b+c)
    {
       int x1, y1, x2, y2;
       int z1 = exgcd(a, b, x1, y1);
       int z2 = exgcd(b, a, x2, y2);
       x1 *= c/z1; x2 *= c/z2;
       int t1 = b/z1, t2 = a/z2;
       x1 = (x1%t1+t1)%t1, x2 = (x2%t2+t2)%t2;//求两个方程的最小正整数解
       y1 = abs(a*x1 - c)/b;
       y2 = abs(b*x2 - c)/a;
       if(x1+y1 < x2+y2)
        cout << x1 << ' ' << y1 << '\n';
       else
        cout << y2 << ' ' << x2 << '\n';
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值