Under construction

Still being built. Things may change

Counting swaps (Hard)

Time limit2sMemory limit1024 MB

Summary
Count the sequences of minimum-length swaps that sort a given permutation, modulo 1e9+9.
Level

Medium7 of 10

Topics
Combinatorics, Math, Implementation
Solved
No attempts yet

Problem

Just like yesterday (problem U of the practice session), Bob is busy, so Alice keeps playing single-player games and puzzles. In her newest puzzle, she has a permutation of the numbers 1 to nn. The goal is to sort the permutation using the smallest possible number of swaps.

Instead of simply solving the puzzle, Alice wants to know the probability of winning by playing at random. To answer this, she needs the number of optimal solutions to the puzzle.

You are given a permutation p1,…,pnp_1, \ldots, p_n of the numbers 1 through nn. In each step, you can choose two numbers x<yx < y and swap pxp_x with pyp_y.

Let mm be the minimum number of such swaps needed to sort the given permutation. Count the number of different sequences of exactly mm swaps that sort the permutation. Since this number may be large, output it modulo 109+910^9 + 9.

Input

The first line contains an integer tt, the number of test cases. Each test case is preceded by a blank line.

Each test case consists of two lines. The first line contains the integer nn. The second line contains the sequence p1,…,pnp_1, \ldots, p_n, a permutation of 1,…,n1, \ldots, n.

Output

For each test case, output a single line containing one integer: x mod (109+9)x \bmod (10^9 + 9), where xx is the number of ways to sort the given sequence using as few swaps as possible.

Constraints

1≤n≤1051 \le n \le 10^5

Hint

In the first test case, we can sort the permutation in two swaps. We can make the first swap in any way, and for each of them there is exactly one optimal second swap. For example, one of the three shortest solutions is "swap p1p_1 with p2p_2 and then swap p1p_1 with p3p_3".

In the second test case, the optimal solution swaps p1p_1 with p2p_2 and p3p_3 with p4p_4. These two swaps can be done in either order.

The third sequence is already sorted. The optimal number of swaps is 0, so the only optimal solution is the empty sequence of swaps.

Examples1

  1. Example 1

    Input
    3
    
    3
    2 3 1
    
    4
    2 1 4 3
    
    2
    1 2
    
    Expected output
    3
    2
    1