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

#SRD0000143. Khoảng cách giữa hai đoạn con (Subarray Distance)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Khoảng cách giữa hai đoạn con (Subarray Distance)

Subarray Distance

Source: MarisaOJ

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a static array AA of nn positive integers. Each of the qq independent queries specifies two index intervals [a,b][a,b] and [c,d][c,d]; the intervals may overlap or coincide.

Their distance is ∑i=ab∑j=cd∣Ai−Aj∣\sum_{i=a}^{b}\sum_{j=c}^{d}|A_i-A_j|. Ordered pairs (i,j)(i,j) are counted: if the intervals coincide, (i,j)(i,j) and (j,i)(j,i) are separate contributions for i≠ji\ne j, whereas pairs with i=ji=j contribute zero.

Calculate the distance for each query. The array does not change.

Input

  • The first line contains n,qn,q.
  • The second line contains nn integers A1,…,AnA_1,\ldots,A_n.
  • Each of the next qq lines contains a,b,c,da,b,c,d, giving two one-based inclusive intervals.

Output

Print qq lines. The tt-th line contains ∑i=ab∑j=cd∣Ai−Aj∣\sum_{i=a}^{b}\sum_{j=c}^{d}|A_i-A_j| for the tt-th query. The answer may exceed a 32-bit integer.

Subtasks

  • Subtask 1 (20 points): 1≤n≤501\le n\le 50; 1≤q≤501\le q\le 50; 1≤Ai≤1091\le A_i\le10^9; 1≤a≤b≤n1\le a\le b\le n; 1≤c≤d≤n1\le c\le d\le n.
  • Subtask 2 (30 points): 1≤n≤20001\le n\le 2000; 1≤q≤20001\le q\le 2000; 1≤Ai≤1091\le A_i\le10^9; 1≤a≤b≤n1\le a\le b\le n; 1≤c≤d≤n1\le c\le d\le n.
  • Subtask 3 (50 points): 1≤n≤1000001\le n\le 100000; 1≤q≤1000001\le q\le 100000; 1≤Ai≤1091\le A_i\le10^9; 1≤a≤b≤n1\le a\le b\le n; 1≤c≤d≤n1\le c\le d\le n.

Examples

Example 1

Input

5 5
1 2 3 4 5
1 1 2 2
1 1 2 3
1 1 2 4
1 2 2 3
1 5 1 5

Output

1
3
6
4
40

Explanation

The first three queries yield respectively ∣1−2∣=1|1-2|=1, ∣1−2∣+∣1−3∣=3|1-2|+|1-3|=3, and 1+2+3=61+2+3=6. The fourth has the four terms ∣1−2∣+∣1−3∣+∣2−2∣+∣2−3∣=4|1-2|+|1-3|+|2-2|+|2-3|=4. For the entire array against itself, every pair of distinct indices contributes twice, yielding 2(4+6+6+4)=402(4+6+6+4)=40.