Counting swaps (Hard)
Time limit2sMemory limit1024 MB
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 . 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 of the numbers 1 through . In each step, you can choose two numbers and swap with .
Let be the minimum number of such swaps needed to sort the given permutation. Count the number of different sequences of exactly swaps that sort the permutation. Since this number may be large, output it modulo .
Input
The first line contains an integer , 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 . The second line contains the sequence , a permutation of .
Output
For each test case, output a single line containing one integer: , where is the number of ways to sort the given sequence using as few swaps as possible.
Constraints
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 with and then swap with ".
In the second test case, the optimal solution swaps with and with . 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.