Editorial for COCI '14 Contest 4 #2 Pšenica


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.

A naive approach to solving this task would be to simulate every move. More precisely, in each move we would find two smallest numbers if it's Mirko's turn, or two biggest numbers if it's Slavko's turn. Then we would make the corresponding change and simulate this procedure until the game is finished. Because the increase of the number of moves is quadratic considering the number of stalks of wheat and we need \mathcal O(n) time to find the smallest/biggest numbers, the total time complexity of this approach is \mathcal O(n^3), which was enough to score 50\% of total points on this task.

By using smarter storage of data, we can save time needed to find the smallest/biggest stalks. For this purpose, we will use the structure deque which enables us to push and pop data from the top or the bottom of the structure in the complexity \mathcal O(1). Each element of the structure is going to be an ordered pair (height, amount) that denotes the number of stalks of wheat for a certain height and the elements are going to be sorted in ascending order according to height (from top to bottom). The search for extremal values now comes down to removing the elements from the top/bottom of the structure. Moreover, the simulation of the game comes down to updating the first two values from the top or the bottom of the structure (depending on who's turn is it. This and similar implementations which have the time complexity \mathcal O(n^2) are sufficient to score 80\% of total points on this task.

Finally, let us notice that, given multiple tallest and shortest stalks, some moves will be repeated. Let's illustrate this with an example. Let the current stalks' heights be \{1, 1, 1, 2, 3, 4, 4, 4\}. The first few moves (if Mirko starts) are going to be:

  • increase 1 to 2
  • decrease 4 to 3
  • increase 1 to 2
  • decrease 4 to 3
  • increase 1 to 2

Only now have we decreased the number of different heights by 1. The state of wheat after these moves is \{2, 2, 2, 2, 3, 3, 3, 4\}.

Using the ideas from previous paragraphs, we can easily analyze the number of shortest and tallest stalks and deduce what the state of wheat will be after the number of different heights is increased by 1. Therefore, in one iteration of the algorithm we will surely decrease the number of elements in the deque structure by 1. This and similar implementations which have the time complexity \mathcal O(n) are sufficient to score 100\% of total points on this task.


Comments

There are no comments at the moment.