Official

F - Best Concatenation Editorial by en_translator


For i=1,2,,Ni = 1, 2, \ldots, N, let XiX_i be the number of X contained in SiS_i, and YiY_i be the sum of digits contained in SiS_i, regarding them as one-digit integers.

Choose an arbitrary permutation P=(P1,P2,,PN)P = (P_1, P_2, \ldots, P_N) of (1,2,,N)(1, 2, \ldots, N) and an integer 1iN11 \leq i \leq N-1. Consider a sequence that is obtained by swapping the ii-th and (i+1)(i+1)-th element of PP, P=(P1,P2,,Pi1,Pi+1,Pi,Pi+2,,PN)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)f(P) of TT corresponding to PP, and the score f(P)f(P') of TT corresponding to PP'.

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

f(P)>f(P)f(P') \gt f(P)

XPi+1YPi>XPiYPi+1(1)\Leftrightarrow X_{P_{i+1}}Y_{P_i} \gt X_{P_i}Y_{P_{i+1}} \tag{1}

YPiXPi>YPi+1XPi+1.(2)\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 ii-th and (i+1)(i+1)-th elements of PP makes the score of TT larger if and only if the inequality (2) holds.

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

Hence, in order to solve this problem, it is sufficient to construct TT by concatenating S1,S2,,SNS_1, S_2, \ldots, S_N in ascending order of Yi/XiY_i/X_i and to print the score of that TT. 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 00.

posted:
last update:



2025-04-08 (Tue)
16:24:09 +00:00