公式

B - 部分文字列の書き換え / Substring Rewriting 解説 by admin

gpt-6-astra-medium

Overview

We examine all substrings of \(S\) of length \(M\), and for each substring, count the number of characters that differ from \(T\). The minimum of these counts is the required number of rewrites.

Analysis

Fixing the position of \(T\)

First, let us decide where the beginning of \(T\) will be placed in the modified string \(S\). Below, we use \(0\)-based indexing and denote this position by \(\mathrm{start}\).

At this time, for each \(j\) (\(0 \leq j < M\)), we need to make \(S[\mathrm{start}+j]\) match \(T[j]\).

  • Characters that already match do not need to be rewritten.
  • Characters that differ must be rewritten.

Therefore, the minimum number of rewrites to form \(T\) at this position is the number of positions where the corresponding characters differ. There is no need to rewrite any characters outside this interval.

For example, when \(S=\texttt{abxdc}\) and \(T=\texttt{abc}\), we have:

Starting position (\(0\)-based) Target substring Number of characters differing from \(T\)
\(0\) abx \(1\)
\(1\) bxd \(3\)
\(2\) xdc \(2\)

We only need to rewrite the x in the first substring to c, so the answer is \(1\).

Searching over starting positions instead of rewrite methods

Trying all combinations of positions to rewrite and their replacement characters results in an enormous number of candidates and will not run in time.

However, once we fix the starting position of \(T\), the required number of rewrites can be found simply by comparing characters. There are \(N-M+1\) possible starting positions, so a brute-force search comparing \(M\) characters for each position is sufficient.

No matter what rewrites are used to achieve the goal, \(T\) will appear somewhere in the resulting \(S\). The number of rewrites required is at least the number of mismatches counted at that starting position, and conversely, rewriting only those mismatched characters achieves the goal. Therefore, the answer is the minimum number of mismatches over all possible starting positions.

Pruning when reaching the current answer

In the code, the minimum value found so far is stored in answer.

While checking a certain starting position, if the number of mismatches changes becomes greater than or equal to answer, further comparisons are unnecessary. Since the number of mismatches will not decrease, that starting position cannot improve the answer.

Moreover, if answer becomes \(0\), no smaller answer can exist, so we can terminate the entire search.

Algorithm

  1. Initialize answer to \(M\). This is because rewriting all characters in an interval of length \(M\) can always make it equal to \(T\).
  2. Try each starting position \(\mathrm{start}\) from \(0\) to \(N-M\) in order:
    1. Set the number of mismatches changes to \(0\).
    2. For \(j=0,1,\ldots,M-1\) in order, compare \(S[\mathrm{start}+j]\) with \(T[j]\).
    3. If they differ, increment changes by \(1\). If changes becomes greater than or equal to answer, abort the comparison for this starting position.
    4. If changes is smaller than answer, update answer.
    5. If answer is \(0\), terminate the entire search.
  3. Output answer.

Complexity

  • Time complexity: \(O((N-M+1)M)\). There are \(N-M+1\) possible starting positions, and up to \(M\) characters are compared for each. Even with the early termination optimization, the worst-case time complexity remains the same.
  • Space complexity: \(O(N+M)\) including the storage of the input strings. The additional space used besides the input is \(O(1)\).

Implementation Notes

  • Since the starting positions range from \(0\) to \(N-M\) inclusive, we use range(n - m + 1).

  • The characters being compared are s[start + j] and t[j]. They can be compared directly without slicing substrings.

  • If the comparison is terminated early, changes may not reflect the total number of mismatches across the entire interval. However, since it is already greater than or equal to answer, this does not affect the answer update.

  • Since this code uses sys.stdin.buffer.readline, s and t are of type bytes. Although indexing into them yields integers, checking whether characters match or differ works just the same.

    Source Code

import sys


def main():
    input = sys.stdin.buffer.readline
    n, m = map(int, input().split())
    s = input().strip()
    t = input().strip()

    answer = m
    for start in range(n - m + 1):
        changes = 0
        for j in range(m):
            if s[start + j] != t[j]:
                changes += 1
                if changes >= answer:
                    break
        if changes < answer:
            answer = changes
            if answer == 0:
                break

    print(answer)


if __name__ == "__main__":
    main()

This editorial was generated by gpt-6-astra-medium.