B - 部分文字列の書き換え / Substring Rewriting Editorial by admin
Claude Opus 5 (High)Overview
We choose one position in a string \(S\) of length \(N\) to “form” \(T\), and rewrite the characters in that interval to match \(T\). The problem asks us to compute the “number of characters differing from \(T\) (Hamming distance)” for every starting position and output the minimum value.
Analysis
Key Observation 1: We only need to rewrite characters within the interval where \(T\) is placed
For \(S\) to ultimately contain \(T\) as a substring, there must exist some starting position \(i\) such that $\(S[i..i+M-1] = T\)\( Conversely, we can achieve our goal simply by rewriting only the characters within this interval to match \)T\(. Modifying characters outside this interval has no effect on the condition of "containing \)T$“, so rewriting them is unnecessary.
Key Observation 2: Fixing the starting position immediately determines the answer
When the starting position \(i\) is fixed, the required number of rewrites is $\(\mathrm{cost}(i) = (\text{number of } k \text{ such that } S[i+k] \neq T[k])\)\( This is because characters that already match do not need to be rewritten, while characters that do not match must be rewritten exactly once. This is precisely the **Hamming distance** between two strings of length \)M$.
Therefore, the answer we seek is $\(\min_{0 \le i \le N-M} \mathrm{cost}(i)\)$
Concrete Example
For \(N=6, M=3\), \(S=\) abcabd, \(T=\) abd:
| Starting position | Substring | Comparison with \(T\) | Cost |
|---|---|---|---|
| 1 | abc |
a=a, b=b, c≠d | 1 |
| 2 | bca |
All mismatch | 3 |
| 3 | cab |
All mismatch | 3 |
| 4 | abd |
All match | 0 |
The minimum value is \(0\), so the answer is \(0\).
Complexity Considerations
There are at most \(N-M+1\) possible starting positions, and comparing at each position takes \(O(M)\) time, giving an overall time complexity of \(O((N-M+1)M)\). Since \(N,M \le 5000\), even in the worst case (\(M \approx N/2 = 2500\)), it requires only about \(2500 \times 2501 \approx 6.3 \times 10^6\) character comparisons, which is fast enough. Therefore, a “brute-force search” is completely fine.
(If \(N\) were around \(10^5\), this naive approach would take \(O(NM)\) and result in TLE, requiring speedups such as bitsets or FFT-based convolution for each alphabet character. However, under the current constraints, this is unnecessary.)
However, because Python has relatively large constant factor overhead, naively writing a nested loop might make \(6.3\times 10^6\) loop iterations slow. Therefore, adding the prunings described below provides peace of mind.
Algorithm
- Initialize the candidate answer
bestto \(M\) (since in the worst case we can rewrite all characters, \(M\) is an upper bound). - For each starting position \(i = 0, 1, \dots, N-M\):
- Compare \(S[i..i+M-1]\) with \(T\) character by character from the beginning, and count the number of mismatches
cnt. - Pruning 1: If
cnt >= bestmidway through, this position cannot update the answer, so terminate the comparison early. - If
cnt < best, updatebest = cnt. - Pruning 2: If
best == 0, it cannot become any smaller, so terminate the entire loop.
- Compare \(S[i..i+M-1]\) with \(T\) character by character from the beginning, and count the number of mismatches
- Output
best.
Complexity
- Time complexity: \(O((N-M+1) \cdot M) = O(N^2)\) (in the worst case where \(N=5000\), about \(6.3 \times 10^6\) character comparisons)
- Space complexity: \(O(N + M)\) (only storing the input strings; slicing a substring takes \(O(M)\))
Implementation Notes
Upper bound on the answer: Since at least one starting position always exists (\(N-M+1 \ge 1\) from the constraint \(M \le N\)), the initial value \(M\) is a valid upper bound that is guaranteed to be updated.
Effective pruning: By executing
breakwhencnt >= best, many positions can be terminated after comparing just a few characters. This is dramatically faster, especially for near-random strings.Using
zip: Writingfor a, b in zip(sub, t)eliminates the need for index calculations and is faster in Python than index-based access.Reading input: Reading everything at once using
sys.stdin.buffer.read().split()speeds up input processing. When reading as byte strings, you can either convert them to strings withdecode()or compare the byte strings directly (comparing directly as byte strings is even faster).Alternative optimization idea (for Python): You can also write
sum(a != b for a, b in zip(s[i:i+m], t))for each starting position, but since pruning cannot be applied, the implementation described above is more advantageous in the worst case. A trickier method involves creating bit integers for each character of the alphabet and computing all at once using&andbit_count().Source Code
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0]); m = int(data[1])
s = data[2].decode()
t = data[3].decode()
best = m
for i in range(n - m + 1):
cnt = 0
sub = s[i:i+m]
for a, b in zip(sub, t):
if a != b:
cnt += 1
if cnt >= best:
break
if cnt < best:
best = cnt
if best == 0:
break
print(best)
main()
This editorial was generated by claude5opus-high.