This is the hard version of the problem. In this version, it is guaranteed that r≥l+k−1…
- User
This is the hard version of the problem. In this version, it is guaranteed that r≥l+k−1
for all queries.
For an arbitrary array b
, Yunli can perform the following operation any number of times:
Select an index i. Set bi=x where x is any integer she desires (x is not limited to the interval [1,n]
).Denote f(b) as the minimum number of operations she needs to perform until there exists a consecutive subarray∗ of length at least k in b
.
Yunli is given an array a of size n and asks you q queries. In each query, you must output ∑rj=l+k−1f([al,al+1,…,aj])
.
∗ If there exists a consecutive subarray of length k that starts at index i (1≤i≤|b|−k+1), then bj=bj−1+1 for all i<j≤i+k−1
. Input
The first line contains t (1≤t≤104
) — the number of test cases.
The first line of each test case contains three integers n , k, and q (1≤k≤n≤2⋅105, 1≤q≤2⋅105
) — the length of the array, the length of the consecutive subarray, and the number of queries.
The following line contains n integers a1,a2,...,an (1≤ai≤n
).
The following q lines contain two integers l and r (1≤l≤r≤n, r≥l+k−1
) — the bounds of the query.
It is guaranteed the sum of n over all test cases does not exceed 2⋅105 and the sum of q over all test cases does not exceed 2⋅105
. Output
Output ∑rj=l+k−1f([al,al+1,…,aj])
for each query on a new line. Example Input Copy
3 7 5 3 1 2 3 2 1 2 3 1 7 2 7 3 7 8 4 2 4 3 1 1 2 4 3 2 3 6 1 5 5 4 2 4 5 1 2 3 1 4 1 5
Output Copy
6 5 2 2 5 2 3
Note
In the second query of the first testcase, we calculate the following function values:
f([2,3,2,1,2])=3because Yunli can set b3=4, b4=5, and b5=6, making a consecutive subarray of size 5 in 3 moves. f([2,3,2,1,2,3])=2 because we can set b3=0 and b2=−1, making a consecutive subarray of size 5 in 2 moves (starting at position 2
)The answer to this query is 3+2=5 . in c++
- Assistant