問題蟲洞: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;
}