Editorial
Problem Author: | Bohdan Feysa |
Editorial by: | Bohdan Feysa |
Let's solve this task when .
The naive solution would be to sort the strings using comparator which checks for two strings if it is true that.
where denotes concantenation of strings and .
However, this aproach could be too slow. There is a faster method of checking which of the following is smaller ( or ). We will be checking this by precomputing hashes of every string and using binary search.
If hash of string is equal to hash of on position then all the symbols of and untill are equal (that means that we assign ). Otherwise at least one symbol is different (so we assign ).
When we found the position in which 'th symbol of is not equal to 'th symbol of we just compare them.
Total time complexity .
When , it is a bit more complicated. The solution is to check manually which string is the most optimal one for reversing. (And if it is actually optimal to reverse one of the strings)
First of all, we will need to store pairs.
For every string in we will precompute hashes. After this we need to use the algorihtm from the solution for .
Right now we have the optimal solution which uses strings, we need to determine which one we will be reversing. For that we will be considering only ones that are smaller when reversed than the original ones.
After we determined the candidates for reversing, we will manually check which string concantenation is lexicographically the smallest one.
For this, we will compute hashes for concantenation of all strings without the reverses.For each reversed string we will store the index in which it should have started if it was included in the resulting string, and the index in which the original string (not reversed) starts.
Let's call the string concantenation if reversed is 'th string. Also, is concantenation in which no string is reversed. In order to check which one is smaller or , we will need several things:
position of strings and in array .
length of all strigns that are not reversed and are placed before our strings
indexes in which reversed strings and start.
indexes in which not reversed strings and start.
Let's check what happens with when we reverse string :
we erase segment which contains string and insert segment of .
So:
As we can see, there are 4 segments which form and the difference between ans is not really that big. If we have computed hashes for , hashes for reversed strings, indexes in which the partition of happens for each needed, we can use the same technique that we used while comparing strings via binary search in block where .
Hence, the total time complexity is equal to .
Please don't forget that this solution has to be optimized as much as possible because there is a huge constant factor that comes out of hashing.