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

#FT0000127. Tổng kép theo hiệu dương (Double Sum)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tổng kép theo hiệu dương (Double Sum)

Double Sum

Source: AtCoder

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a sequence of nonnegative integers A1,…,AnA_1,\ldots,A_n. For every pair of positions i<ji<j, contribute Aj−AiA_j-A_i if it is positive, otherwise contribute zero. Compute

$$\displaystyle S=\sum_{i=1}^{n}\sum_{j=i+1}^{n}\max(A_j-A_i,0).$$

Only the original order of positions matters. Equal values give zero contribution. The answer is guaranteed to fit in a signed 64-bit integer.

Input

  • First line: nn.
  • Second line: A1,…,AnA_1,\ldots,A_n.

Output

Print SS as a signed 64-bit integer.

Subtasks

  • Subtask 1 (20 points): 2≤n≤402\le n\le 40; 0≤Ai≤1080\le A_i\le10^8; the answer is guaranteed to satisfy S<263S<2^{63}.
  • Subtask 2 (30 points): 2≤n≤40002\le n\le 4000; 0≤Ai≤1080\le A_i\le10^8; the answer is guaranteed to satisfy S<263S<2^{63}.
  • Subtask 3 (50 points): 2≤n≤4000002\le n\le 400000; 0≤Ai≤1080\le A_i\le10^8; the answer is guaranteed to satisfy S<263S<2^{63}.

Examples

Example 1

Input

3
2 5 3

Output

4

Explanation

There are exactly three position pairs: (1,2)(1,2) contributes 5−2=35-2=3; (1,3)(1,3) contributes 3−2=13-2=1; (2,3)(2,3) contributes max⁡(3−5,0)=0\max(3-5,0)=0. Total 4.

Example 2

Input

10
5 9 3 0 4 8 7 5 4 0

Output

58

Explanation

For each position jj, sum Aj−AiA_j-A_i over earlier positions with Ai<AjA_i<A_j. For instance, position 2 contributes 9−5=49-5=4 and position 5 contributes (4−3)+(4−0)=5(4-3)+(4-0)=5. Continuing this for all positions gives 58.