Problem solution · Python

ABC371 E — I Hate Sigma Problems

ABC371 E — I Hate Sigma Problems: 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
40 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 ABC371 E — I Hate Sigma Problems, 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

  • 40 lines of Python from the credited upstream file abc371_e.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.

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 codeABC371 E — I Hate Sigma Problems · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def main():    import sys    from itertools import pairwise     input = sys.stdin.readline     n = int(input())    a = list(map(int, input().split()))    s = [[] for _ in range(n)]     # 加算の場合はΣの順番を並び替えても結果は変わらないため、Σの順番を入れ替える    # 各aiについて、一致するなら1、そうでないなら0として、aiを1個以上含む区間の選び方の問題に帰着    # 1個以上を直接数えるのは難しいので、余事象を取る    for i, ai in enumerate(a):        s[ai - 1].append(i)     def nC2(n):        return n * (n - 1) // 2     ans = 0     # 一見するとO(N ** 2)に見えるが、sは全体でN個なのでO(N)    for x in range(n):        excluded = 0         # 端部の処理        for first, second in pairwise([-1] + s[x] + [n]):            excluded += nC2(second - first - 1 + 1)         ans += nC2(n + 1) - excluded     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 ↗