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

#FT0000138. Tổng trọng số sau sắp xếp đoạn (Scalar Queries)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tổng trọng số sau sắp xếp đoạn (Scalar Queries)

Scalar Queries

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a sequence a1,a2,…,ana_1,a_2,\ldots,a_n of pairwise distinct positive integers. For each nonempty contiguous subarray [l,r][l,r]:

  1. Extract the elements al,al+1,…,ara_l,a_{l+1},\ldots,a_r.
  2. Sort them in strictly increasing order as b1,b2,…,br−l+1b_1,b_2,\ldots,b_{r-l+1}.
  3. Compute f(l,r)=∑j=1r−l+1j⋅bjf(l,r)=\sum_{j=1}^{r-l+1}j\cdot b_j. Here jj is the rank after sorting, starting from 11, not the element's original index.

Calculate S=∑1≤l≤r≤nf(l,r)S=\sum_{1\le l\le r\le n}f(l,r) over all nonempty contiguous subarrays, and print S mod (109+7)S\bmod (10^9+7). Different index pairs are counted separately. Single-element subarrays must also be included. Intermediate totals may be very large; take the required modulus.

Input

The first line contains nn. The next line contains exactly nn positive integers a1,a2,…,ana_1,a_2,\ldots,a_n, all distinct.

Output

Print one integer, S mod (109+7)S\bmod(10^9+7), where SS is the weighted sum over every sorted contiguous subarray.

Subtasks

  • Subtask 1 (20 points): 1≤n≤401\le n\le 40; 1≤ai≤1091\le a_i\le 10^9 for all 1≤i≤n1\le i\le n; ai≠aja_i\ne a_j when i≠ji\ne j.
  • Subtask 2 (30 points): 1≤n≤50001\le n\le 5000; 1≤ai≤1091\le a_i\le 10^9 for all 1≤i≤n1\le i\le n; ai≠aja_i\ne a_j when i≠ji\ne j.
  • Subtask 3 (50 points): 1≤n≤5000001\le n\le 500000; 1≤ai≤1091\le a_i\le 10^9 for all 1≤i≤n1\le i\le n; ai≠aja_i\ne a_j when i≠ji\ne j.

Examples

Example 1

Input

4
5 2 4 7

Output

167

Explanation

There are 4⋅5/2=104\cdot5/2=10 subarrays. Their weighted sums are:

Subarray Sorted values f(l,r)f(l,r)
[1,1][1,1] [5][5] 55
[1,2][1,2] [2,5][2,5] 2+2⋅5=122+2\cdot5=12
[1,3][1,3] [2,4,5][2,4,5] 2+8+15=252+8+15=25
[1,4][1,4] [2,4,5,7][2,4,5,7] 2+8+15+28=532+8+15+28=53
[2,2][2,2] [2][2] 22
[2,3][2,3] [2,4][2,4] 2+8=102+8=10
[2,4][2,4] [2,4,7][2,4,7] 2+8+21=312+8+21=31
[3,3][3,3] [4][4] 44
[3,4][3,4] [4,7][4,7] 4+14=184+14=18
[4,4][4,4] [7][7] 77

The total is 5+12+25+53+2+10+31+4+18+7=1675+12+25+53+2+10+31+4+18+7=167, so print 167.

Example 2

Input

3
123456789 214365879 987654321

Output

582491518

Explanation

The six subarrays [1,1][1,1], [1,2][1,2], [1,3][1,3], [2,2][2,2], [2,3][2,3], and [3,3][3,3] have weighted sums 123456789123456789, 552188547552188547, 35151515103515151510, 214365879214365879, 21896745212189674521, and 987654321987654321. The total is 75824915677582491567, giving 582491518 modulo 10000000071000000007.