Power Swapper (Small)

Time limit5sMemory limit512 MB

Summary
Count the ordered swap sequences that sort the permutation when each block size is used at most once on aligned ranges.
Level

Medium6 of 10

Topics
Backtracking, Brute force, Simulation
Solved
No attempts yet

Problem

In a parallel universe people are crazy about powers of two, and they sort permutations of the numbers 1 to 2N2^N with the following swap rule.

  • A range of 2k2^k adjacent numbers is valid only when its starting position is a multiple of 2k2^k. Positions are counted from 0.
  • A swap of size kk exchanges two distinct valid ranges whose lengths are both 2k2^k.

To sort a permutation you may use a swap of size kk at most once for each kk with 0≤k<N0 \le k < N. Swapping a range with itself is not allowed.

For example, the permutation [3,6,1,2,7,8,5,4][3, 6, 1, 2, 7, 8, 5, 4] of the numbers 1 to 232^3 can be sorted like this.

  • [3,6,1,2,7,8,5,4][3, 6, 1, 2, 7, 8, 5, 4]: exchange the ranges [3,6,1,2][3, 6, 1, 2] and [7,8,5,4][7, 8, 5, 4] with a swap of size 2.
  • [7,8,5,4,3,6,1,2][7, 8, 5, 4, 3, 6, 1, 2]: exchange [5][5] and [3][3] with a swap of size 0.
  • [7,8,3,4,5,6,1,2][7, 8, 3, 4, 5, 6, 1, 2]: exchange [7,8][7, 8] and [1,2][1, 2] with a swap of size 1.
  • [1,2,3,4,5,6,7,8][1, 2, 3, 4, 5, 6, 7, 8]: sorting is done.

This run used the sizes 0, 1 and 2 at most once each, and every exchanged range started at a position that is a multiple of its own length.

Count the ways to sort the given permutation under these rules. A way is an ordered sequence of swaps, and two ways are the same only when the sequences are identical. When the permutation is already sorted, the empty sequence that performs no swap counts as one way.

Input

The first line contains the number of test cases TT. TT test cases follow. The first line of each test case contains a single integer NN. The second line contains 2N2^N space separated integers, a permutation of 1,2,…,2N1, 2, \ldots, 2^N.

Limits

  • 1≤T≤2001 \le T \le 200
  • 1≤N≤41 \le N \le 4

Output

For each test case, print one line in the form Case #x: y, where xx is the test case number starting from 1 and yy is the number of ways to sort that permutation under the rules above.

Examples2

  1. Example 1

    Input
    4
    1
    2 1
    2
    1 4 3 2
    3
    7 8 5 6 1 2 4 3
    2
    4 3 2 1
    
    Expected output
    Case #1: 1
    Case #2: 3
    Case #3: 6
    Case #4: 0
    
  2. Example 2

    Input
    4
    1
    1 2
    1
    2 1
    2
    1 2 3 4
    3
    3 6 1 2 7 8 5 4
    
    Expected output
    Case #1: 1
    Case #2: 1
    Case #3: 1
    Case #4: 6