Problem solution · Python

ARC104 B — DNA Sequence

ARC104 B — DNA Sequence: a Python solution using direct simulation. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Direct simulation
Source
KATO-Hiro AtCoder Solutions
Length
45 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Direct simulation

For ARC104 B — DNA Sequence, the implementation follows the problem’s operations directly while maintaining only the state needed for the next decision.

  1. Translate each rule into one explicit state update.
  2. Maintain the invariant after every processed item.
  3. Return the accumulated state once all relevant input has been handled.

Code notes

  • 45 lines of Python from the credited upstream file arc104_b.py.
  • The implementation keeps its working state in language-native values and containers.
  • 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.

Source

Code and credit

This code comes from KATO-Hiro AtCoder Solutions by KATO-Hiro and is used under the CC0-1.0 licence.

Full codeARC104 B — DNA Sequence · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def main():    n, s = input().split()    n = int(n)    ans = 0     # See:    # https://atcoder.jp/contests/arc104/tasks/arc104_b/editorial     # KeyInsight:    # 文字列に含まれるAとT、およびCとGの個数が等しいときに条件を満たす     # 「相補的」という用語の定義・性質を理解するのに時間を要した     # △: どのように文字列の組み合わせの列挙を高速化するか    # →制約から、左端を固定して全探索することができる    # 条件がより厳しい場合は、連想配列に(AとCの個数の差、TとGの個数の差)という形で結果を保持     # △: 文字の数をどのように数えるか    # 例: カウント用の変数を2つ用意し、AとCのときは+1、TとGのときは-1とする    # 管理する変数を減らす    for i in range(n):        a_count, t_count, c_count, g_count = 0, 0, 0, 0         for j in range(i, n):            if s[j] == "A":                a_count += 1            elif s[j] == "T":                t_count += 1            elif s[j] == "C":                c_count += 1            else:                g_count += 1             if (a_count == t_count) and (c_count == g_count):                ans += 1     print(ans)  if __name__ == '__main__':    main() 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗