CF BUDDY
← Problems·

1699C · The Third Problem

1700 · combinatorics, constructive algorithms, math

Problem: You are given a permutation a1,a2,,ana_1,a_2,\ldots,a_n of integers from 00 to n1n - 1. Your task is to find how many permutations b1,b2,,bnb_1,b_2,\ldots,b_n are similar to permutation aa.

Two permutations aa and bb of size nn are considered similar if for all intervals [l,r][l,r] (1lrn1 \le l \le r \le n), the following condition is satisfied: MEX([al,al+1,,ar])=MEX([bl,bl+1,,br]),\operatorname{MEX}([a_l,a_{l+1},\ldots,a_r])=\operatorname{MEX}([b_l,b_{l+1},\ldots,b_r]), where the MEX\operatorname{MEX} of a collection of integers c1,c2,,ckc_1,c_2,\ldots,c_k is defined as the smallest non-negative integer xx which does not occur in collection cc. For example, MEX([1,2,3,4,5])=0\operatorname{MEX}([1,2,3,4,5])=0, and MEX([0,1,2,4,5])=3\operatorname{MEX}([0,1,2,4,5])=3.

Since the total number of such permutations can be very large, you will have to print its remainder modulo 109+710^9+7.

In this problem, a permutation of size nn is an array consisting of nn distinct integers from 00 to n1n-1 in arbitrary order. For example, [1,0,2,4,3][1,0,2,4,3] is a permutation, while [0,1,1][0,1,1] is not, since 11 appears twice in the array. [0,1,3][0,1,3] is also not a permutation, since n=3n=3 and there is a 33 in the array.

Input Format: Each test contains multiple test cases. The first line of input contains one integer tt (1t1041 \le t \le 10^4) — the number of test cases. The following lines contain the descriptions of the test cases.

The first line of each test case contains a single integer nn (1n1051 \le n \le 10^5) — the size of permutation aa.

The second line of each test case contains nn distinct integers a1,a2,,ana_1,a_2,\ldots,a_n (0ai<n0 \le a_i \lt n) — the elements of permutation aa.

It is guaranteed that the sum of nn across all test cases does not exceed 10510^5.

Output Format: For each test case, print a single integer, the number of permutations similar to permutation aa, taken modulo 109+710^9+7.

Note: For the first test case, the only permutations similar to a=[4,0,3,2,1]a=[4,0,3,2,1] are [4,0,3,2,1][4,0,3,2,1] and [4,0,2,3,1][4,0,2,3,1].

For the second and third test cases, the given permutations are only similar to themselves.

For the fourth test case, there are 44 permutations similar to a=[1,2,4,0,5,3]a=[1,2,4,0,5,3]:

  • [1,2,4,0,5,3][1,2,4,0,5,3];
  • [1,2,5,0,4,3][1,2,5,0,4,3];
  • [1,4,2,0,5,3][1,4,2,0,5,3];
  • [1,5,2,0,4,3][1,5,2,0,4,3].

Sample Cases

Case 1

Input

5
5
4 0 3 2 1
1
0
4
0 1 2 3
6
1 2 4 0 5 3
8
1 3 7 2 5 0 6 4

Output

2
1
1
4
72

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback