Problem solution · Python

ABC399 D — Switch Seats

ABC399 D — Switch Seats: 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
59 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 ABC399 D — Switch Seats, 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

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

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 codeABC399 D — Switch Seats · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def solve():    from itertools import pairwise     n = int(input())    a = list(map(lambda x: int(x) - 1, input().split()))    ids = [list() for _ in range(n)]     # 各ペアのインデックスを管理    for i, ai in enumerate(a):        ids[ai].append(i)     # 隣接している異なるペアの候補を集合で管理    candidates = set()     for first, second in pairwise(a):        # 常に first < second となるようにする        if first > second:            first, second = second, first        # 既に隣同士のペアは候補から除外        if first == second:            continue         candidates.add((first, second))     ans = 0     # ペアの候補から条件を満たすものを数える    for x, y in candidates:        xl, xr = ids[x][0], ids[x][1]        yl, yr = ids[y][0], ids[y][1]         # コーナーケース: x か y が隣同士の場合は除外        if xl + 1 == xr:            continue        if yl + 1 == yr:            continue        if abs(xl - yl) == 1 and abs(xr - yr) == 1:            ans += 1     print(ans)  def main():    import sys     input = sys.stdin.readline     t = int(input())     for _ in range(t):        solve()  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 ↗