#P10327. [UESTCPC 2024] 汉诺塔排序问题

[UESTCPC 2024] 汉诺塔排序问题

Problem Description

Natsuzora is playing a Tower of Hanoi with special rules.

There are three pegs, AA, BB, and CC. Disks can be stacked on each peg. Disks may be moved between pegs, but the following rules must be followed:

  • Only one disk can be moved at a time.
  • Each move can only take the top disk of one peg and place it onto the top of another peg.
  • On pegs BB and CC, it is not allowed to place any disk on top of another disk that is smaller than it.
  • On peg AA, it is allowed to place a larger disk on top of a smaller disk.

At the beginning, Natsuzora stacks nn disks of distinct sizes in a random order on peg AA, leaving pegs BB and CC empty. Under the rules above, Natsuzora wants to know the minimum number of moves needed to move all disks from peg AA to peg BB.

Input Format

The first line contains an integer TT (1T104)(1\leq T\leq 10^4), representing the number of test cases.

For each test case, the first line contains an integer nn (1n105)(1\leq n\leq 10^5), representing the number of disks on peg AA in the initial state.

The second line of each test case contains nn integers p1,p2,,pnp_1,p_2,\ldots,p_n (1pin)(1\leq p_i\leq n), where pip_i is the diameter of the ii-th disk on peg AA from bottom to top. The testdata guarantees that p1,p2,,pnp_1,p_2,\ldots,p_n is a permutation of length nn, meaning each integer from 11 to nn appears exactly once in the sequence.

For all test cases, it is guaranteed that n2×105\sum n\leq 2\times 10^5.

Output Format

For each test case, output one integer per line, representing the minimum number of moves required.

3
5
1 5 3 2 4
5
1 2 3 4 5
6
5 3 6 1 4 2
11
5
19

Hint

In the first sample, one feasible move sequence with the minimum number of moves is as follows (XYX\rightarrow Y means moving the top disk of peg XX to the top of peg YY):

  1. ACA\rightarrow C
  2. ABA\rightarrow B
  3. ACA\rightarrow C
  4. BCB\rightarrow C
  5. ABA\rightarrow B
  6. CAC\rightarrow A
  7. CAC\rightarrow A
  8. CBC\rightarrow B
  9. ABA\rightarrow B
  10. ABA\rightarrow B
  11. ABA\rightarrow B

Translated by ChatGPT 5