The Balance POJ - 2142

First, it is possible to know a subject to be solved \ (ax + by = c \ ) equation, and \ (x + y \) minimum.
Inductive Proof:
When \ (a> b \) when, \ (Y \) takes the smallest positive integer solution, \ (B \) Save multiple, \ (A \) increased less, at this time \ (x + y \ ) takes a minimum value. (Similar to the ratio between temperature and heat capacity)
and vice versa.

#include<iostream>
#include<cmath>
#include<cstdlib>
using namespace std;
int a, b, c;
int exgcd(int a, int b, int &x, int &y) {
    if(b == 0) {
        x = 1, y = 0;
        return a;
    }
    int g = exgcd(b, a % b, x, y);
    int tmp = x;
    x = y;
    y = tmp - (a / b) * y;
    return g;
}
void solve(int &x, int &y, int a, int b, int c) {
    int g = exgcd(a, b, x, y); 
    x *= (c / g);
    int t = b / g;
    x = (x % t + t) % t;
    y = (a * x - c) / b;
    y = abs(y);
}
int main() {
    while(cin >> a >> b >> c) {     
        if(!a && !b && !c) break;
        int x1, y1, x2, y2;
        solve(x1, y1, a, b, c); 
        solve(x2, y2, b, a, c);
        if(x1 + y1 < x2 + y2) cout << x1 << " " << y1 << "\n";
        else cout << y2 << " " << x2 << "\n";
    }
    return 0;
} 

Guess you like

Origin www.cnblogs.com/yangxuejian/p/12000277.html