The Balance
Meaning of the questions: a two weights and optimal solution an item (items may be about balance) seeking to make the balance equilibrium given.
Interpretations: ax EQUATIONS + by = c, for x, y are taken positive and negative still on. Conversion for the sake of | x | + | y | optimal solution x = x0 + k * b / gy = y0-k * a / g;
for | x0 + k * b / g | + | y0-k * a / G | optimal solution must be in x0 + k * b / g = 0 and y0-k * a / g = 0, between the two k, traverse just fine. (Piecewise)
#include <bits/stdc++.h> using namespace std; typedef long long ll; void exgcd(ll a,ll b,ll &d,ll &x,ll &y) { if (!b) { d=a; x=1; y=0; return; } exgcd(b,a%b,d,y,x); y-=a/b*x; } int main() { ll a,b,c,d,x,y,ansx,ansy,xx,yy,zz,ans,t; while (scanf("%lld%lld%lld",&a,&b,&c)) { if (a==0&&b==0&&c==0) { break; } exgcd(a,b,d,x,y); x=x*c/d; y=y*c/d; = 0x3f3f3f3f years; t=y/(a/d); zz=-x/(b/d); ansx=abs(x); ansy=abs(y); ans=ansx+ansy; for (ll i=min(zz,t)-1;i<=max(zz,t)+1;i++){ yy=y-a/d*i; //printf("%lld\n",i); if (yy<0) yy=-yy; xx=x+b/d*i; if (xx<0) xx=-xx; if (ans>xx+yy){ ans=xx+yy; ansx=xx; ansy=yy; }else{ if (ans==xx+yy){ if (a*ansx+b*ansy>a*abs(xx)+b*abs(yy)){ ansx=xx; ansy=yy; } } } } printf("%lld %lld\n",ansx,ansy); } return 0; }