公式

F - Best Concatenation 解説 by en_translator


For \(i = 1, 2, \ldots, N\), let \(X_i\) be the number of X contained in \(S_i\), and \(Y_i\) be the sum of digits contained in \(S_i\), regarding them as one-digit integers.

Choose an arbitrary permutation \(P = (P_1, P_2, \ldots, P_N)\) of \((1, 2, \ldots, N)\) and an integer \(1 \leq i \leq N-1\). Consider a sequence that is obtained by swapping the \(i\)-th and \((i+1)\)-th element of \(P\), \(P' = (P_1, P_2, \ldots, P_{i-1}, P_{i+1}, P_i, P_{i+2}, \ldots, P_N)\). Let us compare the score \(f(P)\) of \(T\) corresponding to \(P\), and the score \(f(P')\) of \(T\) corresponding to \(P'\).

As a result of the update from \(P\) to \(P'\), \(T\) loses “the pairs of an X contained in \(S_{P_i}\) and a digit contained in \(S_{P_{i+1}}\),” and gains “the pairs of an X contained in \(S_{P_{i+1}}\) and a digit contained in \(S_{P_i}\).” Thus, \(f(P') - f(P) = X_{P_{i+1}}Y_{P_i} - X_{P_i}Y_{P_{i+1}}\). Therefore, we have

\[f(P') \gt f(P)\]

\[\Leftrightarrow X_{P_{i+1}}Y_{P_i} \gt X_{P_i}Y_{P_{i+1}} \tag{1}\]

\[\Leftrightarrow \frac{Y_{P_i}}{X_{P_i}} \gt \frac{Y_{P_{i+1}}}{X_{P_{i+1}}}. \tag{2}\]

In other words, swapping the \(i\)-th and \((i+1)\)-th elements of \(P\) makes the score of \(T\) larger if and only if the inequality (2) holds.

Therefore, in order to maximize the score of \(T\), let \(P\) be a permutation of \((1, 2, \ldots, N)\) sorted in ascending order of \((1, 2, \ldots, N)\). (Here, if \(X_i= 0\), we consider that \(Y_i/X_i\) takes a value \(\infty\) greater than any real number.)

Hence, in order to solve this problem, it is sufficient to construct \(T\) by concatenating \(S_1, S_2, \ldots, S_N\) in ascending order of \(Y_i/X_i\) and to print the score of that \(T\). 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 \(0\).

投稿日時:
最終更新: