F - Best Concatenation Editorial by en_translator
For , let be the number of X
contained in , and be the sum of digits contained in , regarding them as one-digit integers.
Choose an arbitrary permutation of and an integer . Consider a sequence that is obtained by swapping the -th and -th element of , . Let us compare the score of corresponding to , and the score of corresponding to .
As a result of the update from to ,
loses “the pairs of an X
contained in and a digit contained in ,”
and gains “the pairs of an X
contained in and a digit contained in .”
Thus, .
Therefore, we have
In other words, swapping the -th and -th elements of makes the score of larger if and only if the inequality (2) holds.
Therefore, in order to maximize the score of , let be a permutation of sorted in ascending order of . (Here, if , we consider that takes a value greater than any real number.)
Hence, in order to solve this problem, it is sufficient to construct by concatenating in ascending order of and to print the score of that . In the implementation, it would be simple to implement the inequality (1) instead of (2), because we can stick to integers and handle the exception where the denominator is .
posted:
last update: