A - The Balance
Time Limit:5000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Submit
Status
Practice
POJ 2142
Description
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.
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.
Sample Output
1 3
1 1
1 0
0 3
1 1
49 74
3333 1
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<algorithm>
using namespace std;
const int INF=0x3f3f3f3f;
void extend_gcd(int a,int b,int &x,int &y,int &d)
{
if(!b)
{
x=1;
y=0;
d=a;
return;
}
extend_gcd(b,a%b,x,y,d);
int t=x-a/b*y;
x=y;
y=t;
}
int main()
{
int n,m,p,i;
while(~scanf("%d%d%d",&m,&n,&p))
{
if(!n&&!m&&!p)break;
int x,y,d,flag=0;
if(m<n)
{
flag=1;
swap(m,n);
}
extend_gcd(m,n,x,y,d);
x=x*(p/d);
y=y*(p/d);
int t=y/(m/d),minans=INF,u,v;
for(i=t-1;i<=t+1;i++)
{
int xx=x+n/d*i;
int yy=y-m/d*i;
if(abs(xx)+abs(yy)<minans)
{
minans=abs(xx)+abs(yy);
u=abs(xx);
v=abs(yy);
}
}
if(flag)printf("%d %d\n",v,u);
else printf("%d %d\n",u,v);
}
return 0;
}