【poj2142】The Balance(拓展欧几里得)

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.

Input

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.

题意:

有两个砝码a,b,有一个重物d,a砝码可以使用x个,b砝码可以使用y个,求怎样放置能使天平平衡,并且使用的x+y最小。

题解:

砝码的放置有多种情况
设a=700,b=300
第一种:a在左边b在右边
这里写图片描述
第二种:a在右边,b在左边。
这里写图片描述
第三种:a,b同在左侧。

注意:物品的位置没有影响。

因此可以列方程
ax+by=d;
然后就可以用拓展欧几里得分别求出最小的正整数x,然后带入方程求出对应的y,然后再用拓展欧几里得求最小正整数y,带入方程求对应的x。再将得到的两种(x+y)的值比较,输出小的。

不懂拓展欧几里得的小伙伴可以看一下我写的关于拓展欧几里得的博客

————————–>博客链接

代码:

#include<iostream>
#include<stdio.h>
using namespace std;
typedef long long ll;
ll extgcd(ll a,ll b,ll &x,ll &y)
{
    ll d=a;
    if(b!=0)
    {
        d=extgcd(b,a%b,y,x);
        y-=(a/b)*x;
    }
    else
    {
        x=1; y=0;
    }
    return d;
}
int main()
{
    int a,b,c;
    ll x,y;
    while(scanf("%d%d%d",&a,&b,&c)&&(a||b||c))
    {
       ll  d,x1,y1;
       d=extgcd(a,b,x,y);  //求出x,y   
       //用求出的x得到y
       x1=(x*c/d%(b/d)+b/d)%(b/d);
       y1=(c-a*x1)/b;
       if(y1<0) y1=-y1;
       //用求出y得到x     
       y=(y*c/d%(a/d)+a/d)%(a/d);
       x=(c-b*y)/a;
       if(x<0) x=-x;
       if(x+y>x1+y1)
       {
           x=x1;
           y=y1;
       }
       printf("%I64d %I64d\n",x,y);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lhhnb/article/details/80148274