- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 68 lines of Python from the credited upstream file abc346_d.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
12 3 4def main():5 import sys6 from itertools import accumulate, pairwise7 8 input = sys.stdin.readline9 10 n = int(input())11 s = input().rstrip()12 c = list(map(int, input().split()))13 inf = 10**1814 ans = inf15 one_starts = [0] * n16 zero_starts = [0] * n17 18 19 for i, si in enumerate(s):20 if (i % 2 == 0 and si == "0") or (i % 2 == 1 and si == "1"):21 one_starts[i] = c[i]22 if (i % 2 == 0 and si == "1") or (i % 2 == 1 and si == "0"):23 zero_starts[i] = c[i]24 25 one_starts = list(accumulate(one_starts, initial=0))26 zero_starts = list(accumulate(zero_starts, initial=0))27 28 for i, (si, sj) in enumerate(pairwise(s), 1):29 30 candidate1 = 031 32 if si == "0":33 candidate1 += c[i - 1]34 if sj == "0":35 candidate1 += c[i]36 37 if i % 2 == 1:38 candidate1 += zero_starts[n] - zero_starts[min(n, i + 1)]39 candidate1 += one_starts[max(0, i - 1)]40 else:41 candidate1 += one_starts[n] - one_starts[min(n, i + 1)]42 candidate1 += zero_starts[max(0, i - 1)]43 44 ans = min(ans, candidate1)45 46 47 candidate2 = 048 49 if si == "1":50 candidate2 += c[i - 1]51 if sj == "1":52 candidate2 += c[i]53 54 if i % 2 == 1:55 candidate2 += one_starts[n] - one_starts[min(n, i + 1)]56 candidate2 += zero_starts[max(0, i - 1)]57 else:58 candidate2 += zero_starts[n] - zero_starts[min(n, i + 1)]59 candidate2 += one_starts[max(0, i - 1)]60 61 ans = min(ans, candidate2)62 63 print(ans)64 65 66if __name__ == "__main__":67 main()68