Editorial for COCI '11 Contest 1 #4 Ples
Submitting an official solution before solving the problem yourself is a bannable offence.
For simplicity, let us find partners for boys who wish to dance with shorter girls. The other case is solved analogously, by swapping boys' and girls' heights. The following algorithm solves the problem:
solution := 0
for each boy
find the tallest girl without a partner shorter than him
if no girl was found, continue
pair up the current boy and the girl
solution := solution + 1
A naive implementation of this algorithm has complexity and is worth of points. A key observation is that boys will be paired up with increasingly shorter girls if we iterate over boys from the tallest to the shortest one. This can be implemented with complexity or , where is the maximum height difference. Alternatively, a solution with complexity is also worth all points.
Proof of Correctness
Let us denote by and the boy and the girl, respectively, in the first dance pairing we've made. In every optimal pairing, at least one of them will be paired up. Let us consider two cases:
Only one of them has a partner.
Without loss of generality, assume that the boy is the one who has a partner. If we pair up with instead of his current partner , the number of pairs doesn't decrease.
Both the boy and the girl have a partner.
Let be paired up with a girl , and with a boy . cannot be taller than . is taller than , therefore he is also taller than . Thus the number of pairs doesn't decrease if we pair up with and with .
The first pairing reduces the problem to a smaller problem, which can be solved by the same algorithm.
Comments