Scalar Queries
Source: Codeforces
Version: Phuoc Hung OJ Extended
Problem Statement
You are given a sequence a1,a2,…,an of pairwise distinct positive integers. For each nonempty contiguous subarray [l,r]:
- Extract the elements al,al+1,…,ar.
- Sort them in strictly increasing order as b1,b2,…,br−l+1.
- Compute f(l,r)=∑j=1r−l+1j⋅bj. Here j is the rank after sorting, starting from 1, not the element's original index.
Calculate S=∑1≤l≤r≤nf(l,r) over all nonempty contiguous subarrays, and print Smod(109+7). Different index pairs are counted separately. Single-element subarrays must also be included. Intermediate totals may be very large; take the required modulus.
The first line contains n. The next line contains exactly n positive integers a1,a2,…,an, all distinct.
Output
Print one integer, Smod(109+7), where S is the weighted sum over every sorted contiguous subarray.
Subtasks
- Subtask 1 (20 points): 1≤n≤40; 1≤ai≤109 for all 1≤i≤n; ai=aj when i=j.
- Subtask 2 (30 points): 1≤n≤5000; 1≤ai≤109 for all 1≤i≤n; ai=aj when i=j.
- Subtask 3 (50 points): 1≤n≤500000; 1≤ai≤109 for all 1≤i≤n; ai=aj when i=j.
Examples
Example 1
4
5 2 4 7
Output
167
Explanation
There are 4⋅5/2=10 subarrays. Their weighted sums are:
| Subarray |
Sorted values |
f(l,r) |
| [1,1] |
[5] |
5 |
| [1,2] |
[2,5] |
2+2⋅5=12 |
| [1,3] |
[2,4,5] |
2+8+15=25 |
| [1,4] |
[2,4,5,7] |
2+8+15+28=53 |
| [2,2] |
[2] |
2 |
| [2,3] |
[2,4] |
2+8=10 |
| [2,4] |
[2,4,7] |
2+8+21=31 |
| [3,3] |
[4] |
4 |
| [3,4] |
[4,7] |
4+14=18 |
| [4,4] |
[7] |
7 |
The total is 5+12+25+53+2+10+31+4+18+7=167, so print 167.
Example 2
3
123456789 214365879 987654321
Output
582491518
Explanation
The six subarrays [1,1], [1,2], [1,3], [2,2], [2,3], and [3,3] have weighted sums 123456789, 552188547, 3515151510, 214365879, 2189674521, and 987654321. The total is 7582491567, giving 582491518 modulo 1000000007.