洛谷 - P5656

· · 个人记录

洛谷-P5656 【模板】二元一次不定方程 (exgcd)

题意

ax+by=c

若该方程无整数解,输出 -1。

若该方程有整数解,且有正整数解,则输出其正整数解的数量,所有正整数解中 x 的最小值,所有正整数解中 y 的最小值,所有正整数解中 x 的最大值,以及所有正整数解中 y 的最大值。

若方程有整数解,但没有正整数解,你需要输出所有整数解中 x 的最小正整数值, y 的最小正整数值。

思路

用 exgcd 在求 gcd 时求 a x + b y = \gcd(a, b) 的解。

当 b = 0 时,\gcd(a, b) = a,此时解为 (1, 0)。

通过递归求解其他的解。

所以 \gcd(a, b) 的解为 (y_0, x_0 - \lfloor \frac{a}{b} \rfloor y_0)。

当 c 不为 \gcd(a, b) 的倍数,输出 -1。

代码

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;

int T;
ll a, b, c;
ll x, y;
ll x_1, y_1;
ll x_2, y_2;
ll d;
ll t_min, t_max;
ll m_x, m_y;

ll exgcd(ll a, ll b){
    if(!b){
        x = 1, y = 0;
        return a;
    }
    ll d = exgcd(b, a % b);

    ll x_0 = x, y_0 = y;
    x = y_0;
    y = x_0 - (a / b) * y_0;

    return d;
}

int main(){
    ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    cin >> T;
    while(T --){
        cin >> a >> b >> c;

        d = exgcd(a, b);

        if(c % d){
            cout << -1 << '\n';
            continue;
        }

        x *= c / d;
        y *= c / d;

        t_min = - (x * d) / b;
        t_max = (y * d) / a;

        ///cout << a << ' ' << b << endl;

        if(x + t_min * b / d <= 0){
            t_min ++;
        }
        if(y - t_max * a / d <= 0){
            t_max --;
        }

        ////***
        if(t_max - t_min + 1 <= 0){
            ///cout << "------------------------------------------------------------" << endl;
            m_x = b / d;
            m_y = a / d;

            x_1 = (x % m_x + m_x) % m_x;
            if(x_1 == 0){
                x_1 += m_x;
            }

            y_1 = (y % m_y + m_y) % m_y;
            if(y_1 == 0){
                y_1 += m_y;
            }

            cout << x_1 << ' ' << y_1 << '\n';
        }
        else{
            ///cout << "0000000000000000000000000000000000000000000000000000000000" << endl;
            cout << t_max - t_min + 1 << ' ' << x + t_min * b / d << ' ' << y - t_max * a / d << ' ' << x + t_max * b / d << ' ' << y - t_min * a / d << '\n';
        }
        ///***/
    }

    return 0;
}