UVa Problem Solution: 10090 - Marbles

来源:互联网 发布:网络暴力案例分析ppt 编辑:程序博客网 时间:2024/05/18 00:48

 

This problem requires us to find two non-negative numbers m1 and m2 that satisfying

  n1*m1 + n2*m2 = n

and minimize the cost

  c = c1*m1 + c2*m2.

 

First, we can use extended Euclid's algorithm to find m1' and m2' that give

  n1*m1' + n2*m2' = g

where g is the greatest common divisor of n1 and n2.

 

Now, if g can not divide n, then there's no valid solution. Otherwise, we can get m1'' and m2'' that give

  n1*m1'' + n2*m2'' = n

by multiplying m1' and m2' by n/g.

 

Then we can write m1 and m2 in the following form

  m1 = m1'' + n2/g * t,
  m2 = m2'' - n1/g * t,
where t is a interger parameter, to investigate for which values of t the solution is feasible for our problem. Given

  m1'' + n2/g * t >= 0, m2'' - n1/g * t >= 0, n1 > 0, n2 > 0,

we can get

  -m1'' * g/n2 <= t <= m2'' * g/n1,

and since t must be an integer, we futher have

  ceil(-m1'' * g/n2) <= t <= floor(m2'' * g/n1).
So, all the feasible values of t form an interval of consecutive integer values.

Next, let's look at the cost function

  c = c1*m1 + c2*m2 = (c1*m1'' + c2*m2'') + (c1 * n2/g - c2 * n1/g) * t.

Since both (c1*m1'' + c2*m2'')  and  (c1 * n2/g - c2 * n1/g) are constant values, the cost function is in fact a linear function of t. Thus, its minimum value can occur only at the boundary of the feasible region.

So, we can just check the two boundaries t = ceil(-m1'' * g/n2) and t = floor(m2'' * g/n1), and choose the one yeilding the cheaper cost.

 

 

Code:

原创粉丝点击