#P15495. [ICPC 2025 APC] Tower of Hanoi
[ICPC 2025 APC] Tower of Hanoi
Description
While visiting Hanoi to compete in The ICPC Asia Pacific Championship last year, you learned about the famous Tower of Hanoi problem. In the problem, there are three rods and several disks of distinct radii, which can slide onto any rod. The rods are numbered from to . At any point in time, each disk must be stacked on one of the rods, and the disks stacked on each rod must be arranged in increasing order of radius from top to bottom. In one step, you can move the disk on top of one rod to the top of another rod, provided this move does not violate the restriction above. The goal is to move all the disks to rod in the minimum number of steps.
You are solving an extension of this famous problem. You have a sequence of integers , the initial values of which are given to you.
You are also given operations. Each operation is either of the following:
- Change operation: Two integers and are given. This operation requires you to change the value of to .
- Solve operation: Two integers and are given. This operation requires you to solve the Tower of Hanoi problem with disks of radii , where the disk of radius is initially stacked on rod , for each . The order of the disks initially stacked on each rod satisfies the restriction explained earlier. You need to find the minimum number of steps to move all disks to rod modulo .
Your task is to perform all the given operations sequentially.
Input Format
The first line of input contains two integers and (; ). The second line contains integers representing the initial values of (). The next lines represent the operations in the order they are to be performed. Each line is in one of the following formats:
- "c " (; ) to apply a Change operation for the specified integers and .
- "s " () to apply a Solve operation for the specified integers and .
The input contains at least one Solve operation.
Output Format
For each Solve operation, in order, output the minimum number of steps to solve the Tower of Hanoi problem with disks of radii modulo .
4 4
2 3 1 3
s 2 4
s 1 3
c 3 3
s 2 4
6
2
7
Hint
Explanation for the sample input/output #1
The first operation requires you to solve the Tower of Hanoi problem with disks of radii , , and initially stacked on rods , , and respectively. All disks can be moved to rod in steps as illustrated by Figure D.1.
:::align{center}

Figure D.1: 6 steps to move all disks to rod 1. The shaded rod represents the rod moved on the last step. :::
The second operation requires you to solve the Tower of Hanoi problem with disks of radii , , and initially stacked on rods , , and respectively.
The fourth operation requires you to solve the Tower of Hanoi problem with disks of radii , , and initially stacked on rods , , and respectively.
京公网安备 11011102002149号