Problem solution · Python

ABC167 D — Teleporter

ABC167 D — Teleporter: 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
42 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 ABC167 D — Teleporter, 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

  • 42 lines of Python from the credited upstream file abc167_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 codeABC167 D — Teleporter · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*-  def main():    import sys    input = sys.stdin.readline     n, k = map(int, input().split())    a = list(map(int, input().split()))     # See:    # https://www.youtube.com/watch?v=ENSOy8u9K9I&feature=youtu.be    # KeyInsight:    # 移動: 周期的ではない + 周期的に繰り返すの合計    # 実装上のポイント    # 経路と各点を通った順番を別々に管理する    path = list()    order = [-1 for _ in range(n + 1)]  # -1: 到達していない    place = 1     # 到達していない点がある限り、ループを繰り返す    # = 同じ点を2回通るまで繰り返す    while order[place] == -1:        order[place] = len(path)  # ある場所を通った順番を管理        path.append(place)  # 経路を更新        place = a[place - 1]  # 次の行き先     # 周期: 同じ点を2回通るまでに要した移動回数 - 周期に入るまでの移動回数    cycle = len(path) - order[place]    before_cycle_count = order[place]     if (k < before_cycle_count):        print(path[k])    else:        k -= before_cycle_count        k %= cycle  # 周期: 途中の繰り返し部分を省いて、途中の部分だけ計算するようにする        print(path[before_cycle_count + k])  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 ↗