D - Substring 2 解説 by en_translator
For each length-\(M\) substring of \(S\), we will find the number of operations required to make \(T\) equal to that substring.
Let \(S'\) be the length-\(M\) substring subtracted from \(S\), and define \(f(c_1,c_2)\) as the minimum number of operations required to make \(c_1\) equal to \(c_2\). Then the total number of operations required can be represented as \(\displaystyle \sum_{k=1}^M f(T_k,S'_k)\).
Here, \(f(c_1,c_2)\) can be computed as follows:
- Let \(x_1\) and \(x_2\) be the integer when \(c_1\) and \(c_2\) are regarded as a one-digit integer, respectively.
- If \(x_1 \le x_2\), then \(f(c_1,c_2) = x_2-x_1\).
- If \(x_1 > x_2\), then \(f(c_1,c_2) = x_2-x_1+10\).
Actually, this computation of \(f\) can be simply written as \(f(c_1,c_2) = (x_2-x_1) \bmod 10\). (Note, however, that this expression as is does not gives the desired value in some language, including C++, because of the specification of the modulus operations on negative values.)
The problem can be solved by appropriately implementing the algorithm above.
n, m = map(int, input().split())
s = input()
t = input()
ans = 10**9
for st in range(n - m + 1):
res = 0
for i in range(m):
res += (int(s[st + i]) - int(t[i])) % 10
ans = min(ans, res)
print(ans)
投稿日時:
最終更新: