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.
Output
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.
//356K 0MS
#include<stdio.h>
#include<math.h>
#define inf 0x3f3f3f
int exgcd(int A,int &x,int B,int &y)
{
int x1,y1,x0,y0;
x0=1;y0=0;
x1=0;y1=1;
int r=(A%B+B)%B;
int q=(A-r)/B;
x=0;y=1;
while(r)
{
x=x0-q*x1;
y=y0-q*y1;
x0=x1;
y0=y1;
x1=x;y1=y;
A=B;B=r;r=A%B;
q=(A-r)/B;
}
return B;
}
int main()
{
int a,b,c;
while(scanf("%d%d%d",&a,&b,&c),a|b|c)
{
int x0,y0,flag=0,x,y,min_x,min_y;
if(a<b){flag=a;a=b;b=flag;flag=1;}
int d=exgcd(a,x0,b,y0);
x0=x0*(c/d);//x的一个解
y0=y0*(c/d);//y的一个解
int t=y0/(a/d),min=inf;
for(int i=t-1;i<=t+1;i++)
{
x=x0+b/d*i;
y=y0-a/d*i;
if(fabs(x)+fabs(y)<min)
{
min=fabs(x)+fabs(y);
min_x=fabs(x);
min_y=fabs(y);
}
}
if(flag)printf("%d %d\n",min_y,min_x);
else printf("%d %d\n",min_x,min_y);
}
return 0;
}
具体细节参考https://blog.csdn.net/crescent__moon/article/details/19114095;