Ms. Iyo Kiffa-Australis has a balance and only two kinds of weights to measure a dose of medicine. For example, to measure 200mg of aspirin using 300mg weights and 700mg weights, she can put one 700mg weight on the side of the medicine and three 300mg weights on the opposite side (Figure 1). Although she could put four 300mg weights on the medicine side and two 700mg weights on the other (Figure 2), she would not choose this solution because it is less convenient to use more weights.
You are asked to help her by calculating how many weights are required.
The input is a sequence of datasets. A dataset is a line
containing three positive integers a, b, and d separated by a space. The
following relations hold: a != b, a <= 10000, b <= 10000, and d
<= 50000. You may assume that it is possible to measure d mg using a
combination of a mg and b mg weights. In other words, you need not
consider "no solution" cases.
The end of the input is indicated by a line containing three zeros separated by a space. It is not a dataset.
The output should be composed of lines, each corresponding to an
input dataset (a, b, d). An output line should contain two nonnegative
integers x and y separated by a space. They should satisfy the following
three conditions.
- You can measure dmg using x many amg weights and y many bmg weights.
- The total number of weights (x + y) is the smallest among
those pairs of nonnegative integers satisfying the previous condition.
- The total mass of weights (ax + by) is the smallest among
those pairs of nonnegative integers satisfying the previous two
conditions.
No extra characters (e.g. extra spaces) should appear in the output.
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<cstdlib>
#include<string>
#define eps 0.000000001
typedef long long ll;
typedef unsigned long long LL;
using namespace std;
ll abs1(ll n){
if(n<0)n=-n;
return n;
}
ll gcd(ll a,ll b){
if(b==0)return a;
else{
return gcd(b,a%b);
}
}
ll exgcd(ll a,ll b,ll &x,ll &y){
if(b==0){
x=1;y=0;return a;
}
ll r=exgcd(b,a%b,x,y);
int t=y;
y=x-(a/b)*y;
x=t;
return r;
}
int main(){
ll a,b,c;ll x1,y1,x2,y2;
while(scanf("%I64d%I64d%I64d",&a,&b,&c)!=EOF){
if(a==0&&b==0&&c==0)break;
ll r1=exgcd(a,b,x1,y1);
ll r2=exgcd(b,a,x2,y2);
x1=x1*c/r1;
x2=x2*c/r2;
ll t1=b/r1;
x1=(x1%t1+t1)%t1;
y1=abs1((a*x1-c)/b);
ll t2=a/r2;
x2=(x2%t2+t2)%t2;
y2=abs1((b*x2-c)/a);
if(x1+y1<x2+y2)cout<<x1<<" "<<y1<<endl;
else{
cout<<y2<<" "<<x2<<endl;
}
}
}