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

#CC0000016. Chi phí xây dựng mảng có thứ tự (Create Sorted Array through Instructions)

HỌC THEO LỘ TRÌNH

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

2 lộ trình

Chi phí xây dựng mảng có thứ tự (Create Sorted Array through Instructions)

Create Sorted Array through Instructions

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Start with an empty sorted array and insert a1,a2,…,ana_1,a_2,\ldots,a_n one by one. Before inserting xx, let LL be the number of existing elements strictly less than xx and GG the number strictly greater than xx. The insertion cost is min⁡(L,G)\min(L,G). Find the total cost modulo 109+710^9+7. Equal elements count toward neither LL nor GG.

Input

The first line contains nn, the number of insertions. The next line contains nn integers a1,…,ana_1,\ldots,a_n, to be inserted in order.

Output

Print one integer: the total insertion cost modulo 109+710^9+7.

Subtasks

  • Subtask 1 (20 points): 1≤n≤121\le n\le 12; 1≤ai≤1051\le a_i\le 10^5 for every ii.
  • Subtask 2 (30 points): 1≤n≤13001\le n\le 1300; 1≤ai≤1051\le a_i\le 10^5 for every ii.
  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; 1≤ai≤1051\le a_i\le 10^5 for every ii.

Examples

Input

6
1 2 3 6 5 4

Output

3

Explanation

Inserting 1,2,3,61,2,3,6 costs 00 each because one side is empty. For 55 there are four smaller values and one greater value (66), so the cost is 11. For 44 there are three smaller values (1,2,31,2,3) and two greater values (5,65,6), so the cost is 22. The total is 0+0+0+0+1+2=30+0+0+0+1+2=3.