C - Count ABC Again 解説 by en_translator
If you ignore the constraints, the following solution is valid:
- Modify the \(X_i\)-th character of \(S\) to \(C_i\).
- Inspect the \((N-2)\) length-\(3\) substrings of \(S\), check if each coincides with
ABC
, and print the number of such substrings.
However, \(N\) and \(Q\) can become as large as \(2\times 10^5\), so this solution would result in TLE
(Time Limit Exceeded).
Now notice that modifying one character of \(S\) changes at most three length-\(3\) substrings of \(S\).
For example, suppose that \(S=\) ABCDEFGHI
has become \(S=\) ABCZEFGI
. Before the modification, the length-\(3\) substrings of \(S\) were:
ABC
,BCD
,CDE
,DEF
,EFG
,FGH
,GHI
.
After the modification, it has become:
ABC
,BCZ
,CZE
,ZEF
,EFG
,FGH
,GHI
.
Among them, only three substrings have changed. In general, at most three length-\(3\) substrings will change.
Therefore, it is sufficient to inspect only three substrings that possibly changes, count the number of ABC
before and after modifications, and find the answer after the modification based on the difference and the count before the modification. The complexity is \(O(N+Q)\).
N, Q = map(int, input().split())
S = list(input())
ans = 0
for i in range(N - 2):
if S[i] == "A" and S[i + 1] == "B" and S[i + 2] == "C":
ans += 1
for _ in range(Q):
t, c = input().split()
t = int(t) - 1
for k in range(3):
idx = t - k
if 0 <= idx and idx + 2 < N:
if S[idx] == "A" and S[idx + 1] == "B" and S[idx + 2] == "C":
ans -= 1
S[t] = c
for k in range(3):
idx = t - k
if 0 <= idx and idx + 2 < N:
if S[idx] == "A" and S[idx + 1] == "B" and S[idx + 2] == "C":
ans += 1
print(ans)
投稿日時:
最終更新: