Fire
Time limit2sMemory limit512 MB
Given fire strengths that spread downwind over T steps, answer Q queries for the total fire strength in a range [L, R] at time T.
- Level
Hard8 of 10
- Topics
- Sliding window, Divide and conquer, Prefix sum
- Solved
- No attempts yet
Statement
JOI Village has N districts numbered 1 to N, arranged in a line. A fire breaks out in every district. At time 0, the fire strength in district i is S_i (S_i > 0).
At time 0, the wind blows from district 1 toward district N. For each pair of neighboring districts, if the fire in the upwind district is stronger than the fire in the downwind district at time t (t ≥ 0), the downwind fire at time t+1 takes the strength of the upwind fire at time t. Otherwise, the downwind strength stays the same. Let S_i(t) be the strength of the fire in district i at time t. Then
where S_0(t) = 0 for all t ≥ 0 and S_i(0) = S_i.
You are a firefighter with Q plans, and you carry out exactly one of them. In plan j, you spray extinguishing agent on every district k with L_j ≤ k ≤ R_j. Putting out a fire of strength s takes s liters of agent. So plan j needs S_{L_j}(T_j) + S_{L_j+1}(T_j) + ... + S_{R_j}(T_j) liters. For each plan, compute the amount of agent required.
Input
The first line contains N and Q. The second line contains S_1, S_2, ..., S_N. Each of the next Q lines contains T_j, L_j, and R_j.
N Q
S_1 S_2 ... S_N
T_1 L_1 R_1
...
T_Q L_Q R_Q
Output
Print Q lines. On line j, print the amount of extinguishing agent needed for plan j.
Constraints
- 1 ≤ N ≤ 200 000
- 1 ≤ Q ≤ 200 000
- 1 ≤ S_i ≤ 1 000 000 000 (1 ≤ i ≤ N)
- 1 ≤ T_j ≤ N (1 ≤ j ≤ Q)
- 1 ≤ L_j ≤ R_j ≤ N (1 ≤ j ≤ Q)