POJ 2142 扩展欧几里得

题解

  1. 扩欧求可行解x, y
  2. 分别取对于a, b参数的最小非负整数解情况, 求|x| + |y|最小
  3. 如果2中两种情况绝对值之和相同进一步找最小a|x| + b|y|

code

#include <iostream>
using namespace std;
typedef long long ll;

int a, b, c, x, y;

int extend_gcd(int a, int b, int &x, int &y){
        if(b == 0){
            x = 1;
            y = 0;
            return a;
        }

        int d = extend_gcd(b, a % b, y, x);
        y -= a / b * x;
        return d;
}

inline int Abs(int x) { return x >= 0 ? x : -x;}

int main(){

    while(cin >> a >> b >> c, a + b + c){
        int d = extend_gcd(a, b, x, y);
        if(c % d){
            cout << "no solution" << endl;
            continue;
        }
        x *= c / d, y *= c / d;
        int x1 = (x % (b / d) + b / d) % (b / d);
        int y1 = Abs((c - a * x1) / b);
        int y2 = (y % (a / d) + a / d) % (a / d);
        int x2 = Abs((c - b * y2) / a);
        if(x1 + y1 < x2 + y2)
            cout << x1 << " " << y1 << endl;
        else{
            if(x1 + y1 > x2 + y2)
                cout << x2 << " " << y2 << endl;
            else{
                if(a * x1 + b * y1 <= a * x2 + b * y2) cout << x1 << " " << y1 << endl;
                else cout << x2 << " " << y2 << endl;
            }
        }
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值