-
Notifications
You must be signed in to change notification settings - Fork 1
SRM 528 Colorful Cookie
We are given an array cookies of N (≤50) elements, where cookies[i] is the number of cookies of color i. For each i, have to choose a multiple of P1, say P1xi and a multiple of P2, say P2yi cookies of color i. This must be done in such a way so that each of the xi 'orders' are paired off with some yj order and i≠j.
In order for a choice of xi's and yi's to be a valid pairing, it is necessary and sufficient that for each i, xi≤∑j≠iyj and yi≤∑j≠ixj and ∑xi=∑yi. A straightforward application of Hall's Marriage Theorem yields this condition. Both these equations rearrange to xi+yi≤S for all i, where S=∑xi=∑yi.
For a valid choice of xi's and yi's, the number of cookies that we can eat is ∑(P1xi+P2yi)=(P1+P2)*S. That is, we have to maximize S.
Let us reformulate the problem more precisely. We have to choose (xi,yi)'s such that ∑xi=∑yi=S(say). And for each i, P1xi+P2yi≤cookies[i] and xi+yi<=S. We have to maximize S.
Observe that if some S is attainable, so is S−1. To see this, delete pick a matched pair of orders between xi and yj and decrement both. You can check that all conditions remain satisfied. (We are just taking a perfect bipartite matching and deleting a matched edge along with its endpoints.) Because of this monotonicity property we can binary search for the maximal attainable value of S. So now our problem reduces to: Given S, find out if a configuration with value S is attainable.
Let us try to solve this subproblem with dynamic programming. The first state that comes to mind is f(i,X,Y) = true iff there is some choice of x0..xi and y0..yi with xj+yj≤S and ∑xj = X and ∑yj = Y. This is correct, but since S can be upto 1000 (since each cookies[i]≤2000 and P1,P2 >= 50 we have xi + yi ≤ 2000/50 = 40. And 2S = ∑(xi+yi) ≤ 40.N ≤ 40×50 = 2000, so S≤1000. So this approach has a good chance of getting a TLE.
We can come up with a better approach, by shifting the recurrence parameters around. Define the function g(i,Y) = maximum value of X=∑j=0ixj possible with Y=∑j=0iyj and xj+yj≤S. Suppose when computing g(i,Y) we fix yi, then we should take the highest value of xi as allowed by the constraints, which is max((cookies[i]−P2*yi)/P1,S−yi). yi can range from 0 to cookies[i]/P2 which is at most 40. The number of operations would be around N×1000×40≤2×106. And we do the entire procedure log(1000) times. This should fit well within the time limit.