Editorial for COCI '12 Contest 3 #3 Malcolm
Submitting an official solution before solving the problem yourself is a bannable offence.
A solution that, for each string, iterates over the previous strings and counts the strings with the same number of letters, is too slow.
A faster solution reads a string, counts its letters – let us denote the number of letters with – and then immediately, without another for loop, answers the question: how many strings, out of the previous , have exactly letters?
In order to find that number quickly, we need to keep an auxiliary array with the corresponding count for each . This array must, of course, be maintained: upon reading a new string with length , we increment the element of the auxiliary array by one, and decrement the element by one, where is the length of the string "falling out" of the last strings interval, i.e. not included in the set of friends of upcoming strings anymore.
This solution is actually based on the sweep-line principle: the imaginary scanner is scanning through the rankings list and processing events such as new name added and name removed from friends set.
Comments