Under construction

Still being built. Things may change

Sequence and Queries

Interview

Time limit1sMemory limit1024 MB

Summary
Count triples (i, j, k) where the length-k runs starting at positions i and j satisfy s[i+t] <= s[j+t] for every offset t below k.
Level

Medium4 of 10

Topics
Dynamic programming, Array
Solved
No attempts yet

Problem

A sequence (s1,s2,…,sn)(s_1, s_2, \ldots, s_n) of length nn is given. The function ff is defined as follows.

f(i,j,k)={1if si+t≤sj+t for all 0≤t<k0otherwisef(i,j,k) = \begin{cases} 1 & \text{if } s_{i+t} \leq s_{j+t} \text{ for all } 0 \leq t < k \\ 0 & \text{otherwise} \end{cases}

Print the value of the following sum.

∑i=1n∑j=1n∑k=1min⁡(n−i+1, n−j+1)f(i,j,k)\sum_{i=1}^{n}\sum_{j=1}^{n}\sum_{k=1}^{\min(n-i+1,\, n-j+1)} f(i,j,k)

Input

The first line contains the integer nn, the length of the sequence.

The second line contains nn integers s1,s2,…,sns_1, s_2, \ldots, s_n, separated by spaces.

Output

Print the value of ∑i=1n∑j=1n∑k=1min⁡(n−i+1, n−j+1)f(i,j,k)\sum_{i=1}^{n}\sum_{j=1}^{n}\sum_{k=1}^{\min(n-i+1,\, n-j+1)} f(i,j,k).

Constraints

  • 1≤n≤5 0001\leq n\leq 5\,000
  • 1≤sx≤1091\leq s_x\leq 10^9 (1≤x≤n1\leq x\leq n)

Hint

When i=ji = j, the inequality si+t≤si+ts_{i+t} \leq s_{i+t} holds for every tt, so f(i,i,k)f(i,i,k) is always 1.

Examples2

  1. Example 1

    Input
    2
    2 3
    
    Expected output
    4
    
  2. Example 2

    Input
    5
    2 4 2 2 1
    
    Expected output
    35