Problem solution · Python

ABC186 E — Throne

ABC186 E — Throne: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to KATO-Hiro AtCoder Solutions.

Technique
Depth-first search
Source
KATO-Hiro AtCoder Solutions
Length
46 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

Depth-first search

For ABC186 E — Throne, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 46 lines of Python from the credited upstream file abc186_e.py.
  • The implementation visibly relies on ordered lookup.
  • No explicit loop blocks detected.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

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 codeABC186 E — Throne · PythonPython
Use this to learn the idea, then write your own version.
# -*- coding: utf-8 -*- from typing import Tuple  def extgcd(a: int, b: int) -> Tuple[int, int, int]:    """a * x + b * y = gcd(a, b)     See:    https://qiita.com/drken/items/b97ff231e43bce50199a    https://www.youtube.com/watch?v=hY2FicqnAcc     O(gcd(a, b))    """     if b == 0:        return (a, 1, 0)     g, x, y = extgcd(b, a % b)     return g, y, x - (a // b) * y  def main():    import sys     input = sys.stdin.readline    sys.setrecursionlimit(10 ** 7)     t = int(input())     for i in range(t):        n, s, k = map(int, input().split())        g, x, y = extgcd(k, n)         if s % g != 0:            print(-1)        else:            n, s, k = n // g, s // g, k // g             print((((-s * x) % n) + n) % n)  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 ↗