luogu#P7974. [KSN2021] Delivering Balls

[KSN2021] Delivering Balls

Problem Description

You are given a sequence HH of length NN and QQ queries.

In the ii-th query, you start at column SiS_i and row HSiH_{S_i}, and you want to reach column TiT_i and row HTiH_{T_i}.

You may make several moves. In each move, you can choose the following two parameters:

  • Column 1-1, column unchanged, column +1+1.
  • Row 1-1, row unchanged, row +1+1.

If you choose row 1-1, it costs 11 stamina. If you choose row unchanged, it costs 22 stamina. If you choose row +1+1, it costs 44 stamina.

You must ensure that after each move, your column index xx is within [1,N][1,N], and your row index yy is not less than HxH_x.

For each query, find the minimum stamina cost.

Input Format

The first line contains a positive integer NN.

The second line contains NN positive integers HiH_i.

The third line contains a positive integer QQ.

The next QQ lines each contain two positive integers Si,TiS_i, T_i.

Output Format

For each query, output one line containing an integer, the minimum stamina cost.

4
9 1 8 2
2
1 3
4 2
3
31
9
1 2 3 2 1 2 3 2 1
4
1 9
4 6
2 6
5 2
18
4
9
9

Hint

Sample Explanation

The following figures illustrate the two queries in the first sample:

Constraints

  • Subtask 1 (7 points): There is only one set of testdata, where N=8N=8, Q=4Q=4, H=[,9,3,3,5,4,8,2]H=[,9,3,3,5,4,8,2], and (Si,Ti)(S_i,T_i) are (1,8)(1,8), (3,6)(3,6), (6,4)(6,4), and (7,2)(7,2) in order.
  • Subtask 2 (5 points): Si+1=TiS_i+1=T_i.
  • Subtask 3 (6 points): Hi=iH_i=i.
  • Subtask 4 (18 points): N,Q,Hi100N,Q,H_i\leq 100.
  • Subtask 5 (24 points): N,Q1000N,Q\leq 1000.
  • Subtask 6 (13 points): Si=1S_i=1.
  • Subtask 7 (27 points): No special restrictions.

For all testdata, 2N2×1052\leq N\leq 2\times 10^5, Hi109H_i\leq 10^9, Q2×105Q\leq 2\times 10^5, and 1Si,TiN1\leq S_i,T_i\leq N.

Translated by ChatGPT 5