UVa 10090 - Marbles

Summary
Find k_1 and k_2 such that n_1 m_1 + n_2 m_2 = n minimizing c_1 m_1 + c_2 m_2.

Explanation
Use Extended Euclidean Algorithm to find a solution (probably not optimal). Analyse the cost function to find the optimal.

By definition n_1*x_0 + n_2*y_0 = gcd(n_1, n_2) = g If n/g is not integer, then n is not a linear combination of n_1 and n_2. Failed n_1*x_0*(n/g) + n_2*y_0*(n/g) = n  n_1*[x_0*(n/g) + n_2*t/g] + n_2*[y_0*(n/g) - n_1*t/g] = n Therefore m_1(t) = x_0*(n/g) + n_2*t/g >= 0 // Amount of type1 boxes m_2(t) = y_0*(n/g) - n_1*t/g >= 0 // Amount of type2 boxes

m_1(t) >= 0 -> -x_0*n/n_2 <= t m_2(t) >= 0 -> t <= y_0*n/n_1

-> LOWER_BOUND = -x_0*n/n_2 <= t <= t_0*n/n_1 = UPPER_BOUND... (1)

And about the cost cost(m_1, m_2) = cost(t) = (x_0*c_1+y_0*c_2)*(n/g) + (n_2*c_1-n_1*c_2)*(t/g) = C + M*t -> cost(t) is monotonic. Finally, if exists a t that satisfy (1), then the minimum cost will be at t = ceil( LOWER_BOUND ) or t = floor( UPPER_BOUND )

Gotchas

 * Overflow with 32 bits integer.

Optimizations
Not needed.

Input
9990 3 3 88 89 9991 3 3 88 89 9992 3 3 88 89 9993 3 3 88 89 9994 3 3 88 89 9997 3 3 88 89 10000 3 3 88 89 0

Output
37 111 67 110 8 112 38 111 68 110 69 110 70 110