Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 5905 | Accepted: 2559 |
Description
You are asked to help her by calculating how many weights are required.
Input
The end of the input is indicated by a line containing three zeros separated by a space. It is not a dataset.
Output
- 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.
Sample Input
700 300 200 500 200 300 500 200 500 275 110 330 275 110 385 648 375 4002 3 1 10000 0 0 0
Sample Output
1 3 1 1 1 0 0 3 1 1 49 743333 1
因为要比较大小,所以分别交换系数的值比较两组未知数,因为有常数调整所以整体最小,一定有一个未知数最小
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> using namespace std; int ext_gcd(int a,int b,int &x,int &y); int cal(int a,int b,int c); int main() { int a, b, d; while(scanf("%d %d %d", &a, &b, &d),a||b||d) { int x, y, sum1, ans1, x1, y1, sum2, ans2; x=cal(a,b,d); y=abs((d-a*x)/b); sum1=x+y; ans1=a*x+b*y; x1=cal(b,a,d); y1=abs((d-b*x1)/a); sum2=x1+y1; ans2=b*x1+a*y1; if(sum1<sum2) { printf("%d %d\n",x,y); } else if(sum1==sum2&&ans1<ans2) { printf("%d %d\n",x,y); } else { printf("%d %d\n",y1,x1); } } return 0; } int cal(int a,int b,int c) { int x, y; int d=ext_gcd(a,b,x,y); b/=d; x*=(c/d); if(b<0) { b=-b; } x%=b; if(x<0) { x+=b; } return x; } int ext_gcd(int a,int b,int &x,int &y) { if(b==0) { x=1; y=0; return a; } int ans=ext_gcd(b,a%b,x,y); int tmp=x; x=y; y=tmp-a/b*y; return ans; }