公式

B - Minimize Even Palindrome 解説 by evima


We may assume that the most frequently appearing character in \(S\) is a. Let a appear \(A\) times and other characters appear a total of \(B\) times.

When \(A \le B\)

In this case, we can make \(f(S') = 0\). \(f(S') = 0\) is equivalent to the condition that no two identical characters are adjacent in \(S'\), which can be achieved by the following rearrangement:

  • Let \(S_0\) be the string obtained by rearranging the characters of \(S\) so that a, b, \(\ldots\), z appear in this order.
  • Place the characters of \(S_0\) in order from the front at positions \(1\), \(3\), \(5\), \(\ldots\) (odd positions) sequentially. When odd positions are exhausted, place them at positions \(2\), \(4\), \(\ldots\) (even positions). Let the resulting string be \(S'\).

For example, when \(S =\) abracadabra, we have \(S_0 =\) aaaaabbcdrr, and \(S' =\) abacadararb.

When \(A > B\)

For a string \(s\) consisting of lowercase English letters, let \(\tilde{f}(s)\) denote the number of even-length substrings in \(s\) consisting only of a. Clearly \(\tilde{f}(s) \leq f(s)\). If we can construct one \(S'\) satisfying the following two conditions, that will be the answer:

  • \(S'\) is (one of) the string(s) obtained by rearranging the characters of \(S\) that minimizes \(\tilde{f}(S')\).
  • \(\tilde{f}(S') = f(S')\) holds.

First, we investigate the properties of \(\tilde{f}\). Hereafter, let \(a(n)\) denote the value of \(\tilde{f}(s)\) when \(s\) is a string of \(n\) as. For \(m \geq 0\), \(a(2m) = m^2, a(2m + 1) = m(m+1)\), so \(a(n)\) satisfies the following:

  • Property 1: \(a(n)\) is convex downward. That is, for any \(n \geq 1\), \(2a(n) \leq a(n-1) + a(n+1)\).
  • Property 2: When \(n\) is a positive even number, \(2a(n) = a(n-1) + a(n+1)\).

For \(S'\) obtained by rearranging \(S\), if we split \(S'\) by characters other than a, we obtain \(B+1\) strings consisting only of a (for example, from axaaxay we obtain a, aa, a, and the empty string). Let their lengths be (in order from the front) \(n_1, n_2, \dots, n_{B+1}\), then \(\tilde{f}(S') = \sum_{i = 1}^{B+1} a(n_i)\).

By Property 1, \(\tilde{f}\) is minimized when \(n_i\) are as uniform as possible. Specifically, when \(A = q(B + 1) + r \, (q, r\) are integers with \(0 \leq r \leq B)\), setting \(n_1 = \dots = n_r = q + 1, n_{r + 1} = \dots = n_{B+1} = q\) minimizes \(\tilde{f}(S')\).

In general, for such rearrangements, \(\tilde{f}(S') = f(S')\) does not necessarily hold. However, using Property 2, by repeatedly “if \(n_i\) contains two (or more) even numbers, increase one by \(1\) and decrease the other by \(1\) to make both odd,” we can make \(n_2, \dots, n_{B+1}\) all odd while keeping \(\tilde{f}(S')\) minimal. Then, \(S'\) contains no even-length palindromic substrings other than those consisting only of a, so \(\tilde{f}(S') = f(S')\).

Thus, we have constructed an optimal \(S'\).

投稿日時:
最終更新: