Editorial for COCI '12 Contest 3 #2 Poredak


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.

We need to read two arrays of N strings each and, for every two strings in the first array, find the positions of the same strings in the second array. If the positions are in the correct order, we add 1 to the result; finally, we output the result.

How can we find the position of a string in the second array? One method is using simple for loops, but the resulting time complexity is then \mathcal O(N^2) for choosing all pairs of strings in the first array, times \mathcal O(N) for finding the positions of the two selected strings in the second array (we will ignore the complexity of string comparison, which is proportional to string length), totalling \mathcal O(N^3). For the given N, such a program would be too slow.

In order to reduce the complexity to \mathcal O(N^2), after choosing a pair of strings, we need to immediately (in constant time) find the position of the k^\text{th} string from the first array in the second array. In order to do that, we need to find those positions in advance.

One method is to, before finding the solution, for each k^\text{th} string from the first array, use a for loop to find its position in the second array and store it in an auxiliary array. This sounds similar to the slow method above, but there is an important difference: we iterate over the second array \mathcal O(N) instead of \mathcal O(N^2) times. The total complexity is \mathcal O(N) times \mathcal O(N) for the described auxiliary array precomputation, plus \mathcal O(N^2) for checking all pairs, totalling \mathcal O(N^2), which is fast enough.

Even though it isn't necessary with the given constraints, readers are encouraged to devise an even faster, \mathcal O(N \log N) solution.


Comments

There are no comments at the moment.