Problem solution · Python

ABC359 E — Water Tank

ABC359 E — Water Tank: 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
37 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 ABC359 E — Water Tank, 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

  • 37 lines of Python from the credited upstream file abc359_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 codeABC359 E — Water Tank · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def main():    import sys     input = sys.stdin.readline     n = int(input())    h = list(map(int, input().split()))    stack = []    ans = []    cur_s = 0     # 水槽に水を注いで次の仕切りを超えるためには、階段状の長方形になっている必要がある    # 上記の長方形をstackで管理    for hi in h:        wi = 1         # stackが空でないかつ、stackの最後の要素 <= hiの場合に取り出す        # 計算量: stackから取り出す回数 <= 追加する回数 (<= n)        while stack and stack[-1][0] <= hi:            prev_hj, prev_wj = stack.pop()            wi += prev_wj            cur_s -= prev_hj * prev_wj         stack.append((hi, wi))         cur_s += hi * wi        ans.append(cur_s + 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 ↗