W

Time limit: 0.3s Memory limit: 512MB Input: Output:

Task

An array of numbers is said to be W-shaped if it meets the following conditions:

  1. It consists of four segments in decreasing order, increasing order, decreasing order, increasing order.
  2. The ordering is not strict, so increasing and decreasing segments may include consecutive equal elements.
  3. Every two consecutive segments have a common endpoint.
  4. Every segment contains at least two distinct values.

For example, the array (3 1 2 1 1 4)(3 \ 1 \ 2 \ 1 \ 1 \ 4) is W-shaped, since it consists of the segments (3,1),(1 2),(2 1 1),(1 4)(3, 1), (1 \ 2), (2 \ 1 \ 1), (1 \ 4). The array (3 1 2 2 2 4)(3 \ 1 \ 2 \ 2 \ 2 \ 4) is not W-shaped. It could be broken into the segments (3 1),(1 2),(2 2 2),(2 4)(3 \ 1), (1 \ 2), (2 \ 2 \ 2), (2 \ 4), however the segment (2 2 2)(2 \ 2 \ 2) does not contain two distinct values.

Given an array of NN integers, how many distinct permutations of the array are W-shaped? Two permutations of the array, (p1 p2pN)(p_1 \ p_2 \dots p_N) and (q1 q2qN)(q_1 \ q_2 \dots q_N), are considered distinct if there exists a position 1iN1 ≤ i ≤ N where piqip_i ≠ q_i. In the example above, (3 1 2 1 1 4)(3 \ 1 \ 2 \ 1 \ 1 \ 4) should only be counted once, because permuting the three 11’s does not create distinct permutations.

Input data

The first line contains NN. The second line contains the NN values of the array, separated by spaces.

Output data

Print a single number: the number of distinct W-shaped permutations, modulo 109+710^9 + 7.

Constraints and clarifications

  • 5N300 0005 \leq N \leq 300 \ 000
  • Array values are integers between 11 and 1 000 0001 \ 000 \ 000 inclusive.
  • Test cases will be scored individually.
# Points Constraints
1 20 There are only two distinct values among the NN elements.
2 30 All the NN elements have distinct values.
3 50 No additional constraints.

Example 1

stdin

5
3 1 4 2 3

stdout

6

Explanation

The six distinct W-shaped permutations are:

  • 3 1 3 2 43 \ 1 \ 3 \ 2 \ 4
  • 3 1 4 2 33 \ 1 \ 4 \ 2 \ 3
  • 3 2 3 1 43 \ 2 \ 3 \ 1 \ 4
  • 3 2 4 1 33 \ 2 \ 4 \ 1 \ 3
  • 4 1 3 2 34 \ 1 \ 3 \ 2 \ 3
  • 4 2 3 1 34 \ 2 \ 3 \ 1 \ 3

Example 2

stdin

7
1 2 2 2 3 4 4

stdout

72

Log in or sign up to be able to send submissions!