PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000106. Đếm bộ bốn tăng đan xen (Count Increasing Quadruplets)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đếm bộ bốn tăng đan xen (Count Increasing Quadruplets)

Count Increasing Quadruplets

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a permutation a=(a1,a2,…,an)a=(a_1,a_2,\ldots,a_n) of the integers from 11 to nn. Every integer occurs exactly once, and positions are numbered from 11 through nn.

Consider any quadruple of indices (i,j,k,l)(i,j,k,l) satisfying 1≤i<j<k<l≤n1\le i<j<k<l\le n. The quadruple is valid exactly when the values at these indices satisfy

ai<ak<aj<al.a_i<a_k<a_j<a_l.

Thus the values do not need to be increasing in index order: in particular, the value at the third selected position must be smaller than the value at the second selected position, even though j<kj<k.

Count all valid quadruples of indices. Two quadruples are different if at least one index differs. The answer may exceed the range of a 32-bit signed integer.

Input

  • The first line contains the integer nn, the length of the permutation.
  • The second line contains exactly nn integers a1,a2,…,ana_1,a_2,\ldots,a_n, in index order from 11 through nn.

Output

Print one integer: the number of quadruples (i,j,k,l)(i,j,k,l) satisfying both i<j<k<li<j<k<l and ai<ak<aj<ala_i<a_k<a_j<a_l.

Subtasks

  • Subtask 1 (20 points): 4≤n≤124\le n\le 12; aa is a permutation of 1,2,…,n1,2,\ldots,n (every value occurs exactly once).
  • Subtask 2 (30 points): 4≤n≤3504\le n\le 350; aa is a permutation of 1,2,…,n1,2,\ldots,n (every value occurs exactly once).
  • Subtask 3 (50 points): 4≤n≤40004\le n\le 4000; aa is a permutation of 1,2,…,n1,2,\ldots,n (every value occurs exactly once).

Examples

Example 1

Input

5
1 3 2 4 5

Output

2

Explanation

The only qualifying middle pair is (j,k)=(2,3)(j,k)=(2,3), with values 3>23>2. Index i=1i=1 contributes value 1<21<2. We may choose either l=4l=4 (value 44) or l=5l=5 (value 55); both exceed 33. Thus exactly (1,2,3,4)(1,2,3,4) and (1,2,3,5)(1,2,3,5) qualify, giving 2.

Example 2

Input

4
1 2 3 4

Output

0

Explanation

The only quadruple of indices is (1,2,3,4)(1,2,3,4), but aj=2<ak=3a_j=2<a_k=3 whereas the required condition is ak<aja_k<a_j. Therefore the answer is 0.