#P1736C2. Good Subarrays (Hard Version)

    ID: 7992 Type: RemoteJudge 3000ms 256MiB Tried: 0 Accepted: 0 Difficulty: (None) Uploaded By: Tags>binary searchdata structuresdptwo pointers

Good Subarrays (Hard Version)

No submission language available for this problem.

Description

This is the hard version of this problem. In this version, we have queries. Note that we do not have multiple test cases in this version. You can make hacks only if both versions of the problem are solved.

An array bb of length mm is good if for all ii the ii-th element is greater than or equal to ii. In other words, bb is good if and only if biib_i \geq i for all ii (1im1 \leq i \leq m).

You are given an array aa consisting of nn positive integers, and you are asked qq queries.

In each query, you are given two integers pp and xx (1p,xn1 \leq p,x \leq n). You have to do ap:=xa_p := x (assign xx to apa_p). In the updated array, find the number of pairs of indices (l,r)(l, r), where 1lrn1 \le l \le r \le n, such that the array [al,al+1,,ar][a_l, a_{l+1}, \ldots, a_r] is good.

Note that all queries are independent, which means after each query, the initial array aa is restored.

The first line contains a single integer nn (1n21051 \le n \le 2 \cdot 10^5).

The second line contains nn integers a1,a2,,ana_1, a_2, \ldots, a_n (1ain1 \le a_i \le n).

The third line contains an integer qq (1q21051 \leq q \leq 2 \cdot 10^5) — the number of queries.

Each of the next qq lines contains two integers pjp_j and xjx_j (1pj,xjn1 \leq p_j, x_j \leq n) – the description of the jj-th query.

For each query, print the number of suitable pairs of indices after making the change.

Input

The first line contains a single integer nn (1n21051 \le n \le 2 \cdot 10^5).

The second line contains nn integers a1,a2,,ana_1, a_2, \ldots, a_n (1ain1 \le a_i \le n).

The third line contains an integer qq (1q21051 \leq q \leq 2 \cdot 10^5) — the number of queries.

Each of the next qq lines contains two integers pjp_j and xjx_j (1pj,xjn1 \leq p_j, x_j \leq n) – the description of the jj-th query.

Output

For each query, print the number of suitable pairs of indices after making the change.

Sample Input 1

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

Sample Output 1

6
10
5

Sample Input 2

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

Sample Output 2

7
9
8

Note

Here are notes for first example.

In first query, after update a=[2,4,1,4]a=[2,4,1,4]. Now (1,1)(1,1), (2,2)(2,2), (3,3)(3,3), (4,4)(4,4), (1,2)(1,2), and (3,4)(3,4) are suitable pairs.

In second query, after update a=[2,4,3,4]a=[2,4,3,4]. Now all subarrays of aa are good.

In third query, after update a=[2,1,1,4]a=[2,1,1,4]. Now (1,1)(1,1), (2,2)(2,2), (3,3)(3,3), (4,4)(4,4), and (3,4)(3,4) are suitable.