#P1227D2. Optimal Subsequences (Hard Version)
Optimal Subsequences (Hard Version)
Description
This is the harder version of the problem. In this version, . You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems.
You are given a sequence of integers of length . Its subsequence is obtained by removing zero or more elements from the sequence (they do not necessarily go consecutively). For example, for the sequence :
- , , , , are subsequences (these are just some of the long list);
- , , , are not subsequences.
Suppose that an additional non-negative integer () is given, then the subsequence is called optimal if:
- it has a length of and the sum of its elements is the maximum possible among all subsequences of length ;
- and among all subsequences of length that satisfy the previous item, it is lexicographically minimal.
Recall that the sequence is lexicographically smaller than the sequence if the first element (from the left) in which they differ less in the sequence than in . Formally: there exists () such that , , ..., and at the same time . For example:
- lexicographically less than ,
- is lexicographically less than ,
- is lexicographically less than .
You are given a sequence of and requests, each consisting of two numbers and (, ). For each query, print the value that is in the index of the optimal subsequence of the given sequence for .
For example, if , , , then the optimal subsequence is — it is the minimum lexicographically among all subsequences of length with the maximum total sum of items. Thus, the answer to the request , is the number , and the answer to the request , is the number .
The first line contains an integer () — the length of the sequence .
The second line contains elements of the sequence : integer numbers ().
The third line contains an integer () — the number of requests.
The following lines contain pairs of integers and (, ) — the requests.
Print integers () one per line: answers to the requests in the order they appear in the input. The value of should be equal to the value contained in the position of the optimal subsequence for .
Input
The first line contains an integer () — the length of the sequence .
The second line contains elements of the sequence : integer numbers ().
The third line contains an integer () — the number of requests.
The following lines contain pairs of integers and (, ) — the requests.
Output
Print integers () one per line: answers to the requests in the order they appear in the input. The value of should be equal to the value contained in the position of the optimal subsequence for .
Note
In the first example, for the optimal subsequences are:
- for : ,
- for : ,
- for : .