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

#FT0000051. Dãy con tối ưu – phiên bản khó (Optimal Subsequences (Hard Version))

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Dãy con tối ưu – phiên bản khó (Optimal Subsequences (Hard Version))

Optimal Subsequences (Hard Version)

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

A subsequence of a1,…,ana_1,\ldots,a_n selects positions in strictly increasing order; chosen positions need not be consecutive. For every length kk, an optimal subsequence is one with maximum element sum, and among those with that maximum sum it is lexicographically smallest. Sequences are compared at their first differing element; the smaller element makes the sequence lexicographically smaller. Equal value sequences are equivalent.

Each of mm independent queries supplies kk and pp. Output the value at the one-based position pp of the optimal length-kk subsequence. The input sequence remains unchanged.

Input

  • Line 1: integer nn, the length.
  • Line 2: exactly nn integers a1,…,ana_1,\ldots,a_n.
  • Line 3: integer mm, the number of queries.
  • Next mm lines: query jj contains kj,pjk_j,p_j specifying the subsequence length and the requested position.

Output

Print mm lines, one integer per query, in the original query order.

Subtasks

Subtask 1 (20 points):

  • 1≤n,m≤201\le n,m\le 20; 1≤ai≤1091\le a_i\le10^9 for every ii; 1≤pj≤kj≤n1\le p_j\le k_j\le n for every query jj.

Subtask 2 (30 points):

  • 1≤n,m≤20001\le n,m\le 2000; 1≤ai≤1091\le a_i\le10^9 for every ii; 1≤pj≤kj≤n1\le p_j\le k_j\le n for every query jj.

Subtask 3 (50 points):

  • 1≤n,m≤2000001\le n,m\le 200000; 1≤ai≤1091\le a_i\le10^9 for every ii; 1≤pj≤kj≤n1\le p_j\le k_j\le n for every query jj.

Examples

Examples 1

Input

3
10 20 10
6
1 1
2 1
2 2
3 1
3 2
3 3

Output

20
10
20
10
20
10

Explanation

For k=1k=1, the best subsequence is [20][20]. For k=2k=2, both [10,20][10,20] and [20,10][20,10] total 3030, but [10,20][10,20] is lexicographically smaller. For k=3k=3, the entire sequence [10,20,10][10,20,10] is required. Reading the six requested positions yields the shown six answers.

Examples 2

Input

4
10 20 30 20
3
2 1
2 2
4 3

Output

20
30
30

Explanation

The maximum sum for length two is 5050. Among [20,30][20,30] and [30,20][30,20], choose [20,30][20,30] by the lexicographic tie-break. For length four, the whole sequence is selected, whose third value is 3030.