Editorial for COCI '13 Contest 3 #4 Kolinje


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

People from 1 to N are going to get, respectively, B_1 X, B_2 X, \dots, B_N X kilos of ham, given an X. We need to find X such that the sequence is correct; from it, it is easy to calculate the total number of distributed kilos.

We want the following to be true: A_1 + B_1 X \ge A_2 + B_2 X \ge \dots \ge A_N + B_N X.

Let us analyze the first inequality; the rest are analyzed analogously. From A_1 + B_1 X \ge A_2 + B_2 X follows (B_1-B_2)X \ge A_2-A_1.

We'd like to divide this inequality by B_1-B_2 so only X is left on the left side. However, we need to be careful!

If B_1-B_2 = 0, we cannot make the division, but the inequality turns into 0 \ge A_2-A_1. In this case, if A_2-A_1 > 0, we output -1 because this is a contradiction. Otherwise, the inequality is valid so we move on to the next one.

If B_1-B_2 \ne 0, we can make the division, but dividing by a negative number changes the inequality signs so we either get X \ge (A_2-A_1)/(B_1-B_2) or X \le (A_2-A_1)/(B_1-B_2). In one case we got the lower, and in the other the upper bound for X.

Repeating this operation for all N-1 inequalities, we gathered some lower and upper bounds for X. Of all the lower bounds, we are interested in only the greatest (because it implies all the rest), and of all the upper bounds, we are interested in only the smallest (because it implies all the rest). If between those two bounds there is a number, that is, if the lower bound is smaller or equal to the upper, a solution exists: we can use the average of the lower and upper bound as X. Otherwise, the solution does not exist.

The task is also solvable with binary search; we leave the details for the reader to practise.


Comments

There are no comments at the moment.