Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque. We call this sequence of actions an operation.
For example, if deque was [2, 3, 4, 5, 1], on the operation he will write B=3 to the beginning and A=2 to the end, so he will get [3, 4, 5, 1, 2].
The teacher of the course, seeing Valeriy, who was passionate about his work, approached him and gave him q queries. Each query consists of the singular number m_j (j = 1, 2, …, q). It is required for each query to answer which two elements he will pull out on the m_j-th operation.
Note that the queries are independent and for each query the numbers A and B should be printed in the order in which they will be pulled out of the deque.
Deque is a data structure representing a list of elements where insertion of new elements or deletion of existing elements can be made from both sides.
Input
The first line contains two integers n and q (2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3 ⋅ 10^5) — the number of elements in the deque and the number of queries. The second line contains n integers a_1, a_2, ..., a_n, where a_i (0 ≤ a_i ≤ 10^9) — the deque element in i-th position. The next q lines contain one number each, meaning m_j (1 ≤ m_j ≤ 10^{18}).
Output
For each teacher's query, output two numbers A and B — the numbers that Valeriy pulls out of the deque for the m_j-th operation.
Examples
Input
5 3
1 2 3 4 5
1
2
10
Output
1 2
2 3
5 2
Input
2 0
0 0
Output
Note
Consider all 10 steps for the first test in detail:
[1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively.
So, 2 we write to the beginning of the deque, and 1 — to the end.
We get the following status of the deque: [2, 3, 4, 5, 1].
[2, 3, 4, 5, 1] ⇒ A = 2, B = 3.
[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]
[5, 1, 2, 3, 4]
[5, 2, 3, 4, 1]
[5, 3, 4, 1, 2]
[5, 4, 1, 2, 3]
[5, 1, 2, 3, 4]
[5, 2, 3, 4, 1] ⇒ A = 5, B = 2.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to solve problem: given initial deque of n elements (n up to 1e5), we repeatedly perform operation: take first two elements (A = front, B = second). If A > B, then we move A to front? Actually careful: "if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque." Let's parse: after removing A and B, we need to write something to the beginning (i.e., push front) and something to the end (push back). Specifically:
If A > B: writes A to the beginning (so push front A) and writes B to the end (push back B).
else (A <= B): writes B to the beginning and A to the end.
So after operation, deque's new state: first element is the winner (max(A,B))? Actually note: if A > B, then A is larger, so A goes to front, B to back. If A <= B, then B is larger or equal, B goes to front, A to back. So effectively, after operation, the larger of the two becomes new front, and the smaller goes to the back. This resembles a process similar to "queue" where the front element competes with next and the loser goes to back, but here the winner stays at front? Wait typical "queue" process (like in problem "Fighting" from Codeforces) is: we take two from front, compare, winner goes to front, loser to back. That's exactly: we remove first two, then push the winner to the front? But careful: after removing, we need to insert at front and back. The typical process: after taking two, you put the larger one in front and the smaller at the back. That is exactly as described. In that known problem, the maximum element eventually becomes the front and stays there after enough steps, and the rest cycle. In that known problem (CF "Fight Against Traffic" maybe?), but there's known CF problem: "Little Pony and Sort by Shift"? Not that. Actually known: Codeforces problem "A. Game With Sticks"? No.
I recall Codeforces Round # I think "Fight Against Traffic" is not. But I know a problem: "A. Queue" or "A. Cards" maybe. There is a problem: "A. DZY loves chessboard"? No.
Better to think: This is analogous to process where you have a deck and you repeatedly take top two, winner goes to top, loser goes to bottom. In known solution: after first n-1 steps (or after some steps) the maximum element becomes the first and thereafter the process cycles with period n-1, with the first element fixed (the maximum) and the rest rotate. Actually let's simulate small examples.
Take n=5: elements: [1,2,3,4,5]. In each step, front is max? Let's simulate given example:
Start: [1,2,3,4,5]
step1: A=1,B=2, since 1<2, so B=2 to front, A=1 to back => [2,3,4,5,1]
step2: A=2,B=3 => 2<3 => B=3 front, A=2 back => [3,4,5,1,2]
step3: A=3,B=4 => 3<4 => [4,5,1,2,3]
step4: A=4,B=5 => 4<5 => [5,1,2,3,4]
step5: A=5,B=1 => 5>1 => A=5 front? Wait condition: if A>B => writes A to beginning, B to end. So after step5, we have front=5? Actually we remove A=5,B=1, since 5>1, we push A to front, B to end. So new deque: we start with front: push front A=5, then the rest of deque after removal? The deque after removal of first two originally is [2,3,4]? Wait before step5: deque = [5,1,2,3,4] (after step4). Removing first two: remove 5 and 1, remaining [2,3,4]. Then we push front A (5) and push back B (1). So new deque: front: 5, then [2,3,4], then back: 1 => [5,2,3,4,1]. That's step6? Actually they list steps: step5 gave [5,1,2,3,4]? Let's check the example details: They gave steps:
1: [1,2,3,4,5] -> after step: [2,3,4,5,1]
2: [2,3,4,5,1] -> A=2,B=3 => [3,4,5,1,2]
3: -> [4,5,1,2,3]
4: -> [5,1,2,3,4]
5: -> [5,2,3,4,1] (from example: step6? Actually they list: after step5 they get [5,2,3,4,1]? Let's re-check example statement:
"Consider all 10 steps for the first test in detail:
[1, 2, 3, 4, 5] — on the first operation, A and B are 1 and 2, respectively.
So, 2 we write to the beginning of the deque, and 1 — to the end.
We get the following status of the deque: [2, 3, 4, 5, 1].
[2, 3, 4, 5, 1] ⇒ A = 2, B = 3.
[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]
[5, 1, 2, 3, 4]
[5, 2, 3, 4, 1]
[5, 3, 4, 1, 2]
[5, 4, 1, 2, 3]
[5, 1, 2, 3, 4]
[5, 2, 3, 4, 1] ⇒ A = 5, B = 2."
Wait they have step numbers: after step1 state is [2,3,4,5,1]. Then they say "2. [2,3,4,5,1] => A=2,B=3." That means step2 is performed on that state. So step2 produces something; they don't show state after step2 explicitly? Actually they show "3. [3,4,5,1,2]" which is state after step2? Let's parse:
Step1: initial [1,2,3,4,5] -> after op state1: [2,3,4,5,1].
Step2: starting from state1, perform op => after op state2: [3,4,5,1,2]. They denote "3. [3,4,5,1,2]" meaning after step2? Actually they number the states after each step? They wrote:
[1,2,3,4,5] — on the first operation, ... So that's initial state.
Then "We get the following status of the deque: [2, 3, 4, 5, 1]."
[2, 3, 4, 5, 1] ⇒ A = 2, B = 3.
[3, 4, 5, 1, 2]
[4, 5, 1, 2, 3]
[5, 1, 2, 3, 4]
[5, 2, 3, 4, 1]
[5, 3, 4, 1, 2]
[5, 4, 1, 2, 3]
[5, 1, 2, 3, 4]
[5, 2, 3, 4, 1] ⇒ A = 5, B = 2.
It seems they enumerate steps: line "1." is the initial state before any operation; "2." is the state before step2? Actually they say "2. [2,3,4,5,1] ⇒ A = 2, B = 3." That means at step2, the deque is [2,3,4,5,1] and A=2,B=3. Then after step2, the deque becomes [3,4,5,1,2] which they list as "3. [3,4,5,1,2]". So "3." likely denotes the state after step2. But they also label "10. [5,2,3,4,1] ⇒ A=5,B=2" meaning at step10, before operation, deque is [5,2,3,4,1] and A=5,B=2? Actually step10's operation yields something, but they are showing the state before step10? Let's check: They start with step1: before step1 deque [1,2,3,4,5]; after step1 becomes [2,3,4,5,1]. So step2 deque before op is [2,3,4,5,1] and they show that as "2. [2,3,4,5,1] => A=2,B=3". Then after step2, deque becomes [3,4,5,1,2] which they show as "3. [3,4,5,1,2]". So it seems they are showing the state after each step? But then "3." is after step2, "4." after step3, etc. And they also show for step10: "10. [5,2,3,4,1] ⇒ A = 5, B = 2." That would be the state after step9 (i.e., before step10) and they indicate that at step10, A and B are 5 and 2. So for query m_j=10, answer is (5,2). For m_j=2, answer (2,3) as they show step2: before step2, A=2,B=3? Actually step2's A and B are (2,3) from deque [2,3,4,5,1]. So answer for m=2 is (2,3). For m=1, (1,2). So the pattern: at step m, we take the first two elements of the deque at the beginning of that step (before performing operation). So we need to output those two numbers.
Thus problem: we have process defined by operation; given huge m (up to 1e18), we need to know which two elements are at positions 0 and 1 (front and second) at the start of m-th operation. Queries are independent; we don't need to simulate up to m for each query.
Observations: This process is deterministic. After some initial steps, the maximum element becomes the first and stays there forever? Let's check example: after step4 (or step5?) we have maximum 5 at front? Actually after step4, before step5? Let's see: After step4? They list "5. [5,1,2,3,4]" which is state after step4? Actually they label "5. [5,1,2,3,4]" that's after step4? Let's reorder:
Before any steps: state0 = [1,2,3,4,5].
After step1: state1 = [2,3,4,5,1].
After step2: state2 = [3,4,5,1,2].
After step3: state3 = [4,5,1,2,3].
After step4: state4 = [5,1,2,3,4].
After step5: state5 = [5,2,3,4,1] (since "6. [5,2,3,4,1]" is state5)
After step6: state6 = [5,3,4,1,2]
After step7: state7 = [5,4,1,2,3]
After step8: state8 = [5,1,2,3,4]
After step9: state9 = [5,2,3,4,1]
After step10: state10 = ??? Not given, but would be [5,3,4,1,2] perhaps? But they stopped.
Thus from step4 onward (state4), the first element is 5 (the maximum). However, after state4, we see that first element stays 5 in all subsequent states. So indeed, once the maximum reaches the front, it never leaves because it will always be compared with the second element: if it is larger (which it is, since it's maximum of all elements), then condition A > B holds, so after operation, we push A to front (which is the max) and B to back, so the max remains at front. So after max becomes front, it stays front forever.
Now, the sequence of the second element (and the rest) seems to rotate? In states after max is front: state4: [5,1,2,3,4]; state5: [5,2,3,4,1]; state6: [5,3,4,1,2]; state7: [5,4,1,2,3]; state8: [5,1,2,3,4] again, etc. So the tail (positions 1..n-1) cycles with period n-1 = 4. In each operation, the front (max) stays, and the second element (which is compared) gets moved to the back after being the loser (since max > second, so second goes to back). So essentially, after max is front, each operation rotates the tail left? Let's see: Starting from [5,1,2,3,4], operation: A=5,B=1, since 5>1, we push front A=5 (same), and push back B=1 => the order becomes: front 5, then the previous tail without the first element? The deque after removal of first two: after removing 5 and 1, remaining is [2,3,4]; then push front 5, push back 1 => [5,2,3,4,1]. So indeed the tail after the operation is the previous tail rotated: originally tail (starting from index 1) is [1,2,3,4]. After operation, new tail is [2,3,4,1]. So it's a left rotation of the tail by one? Actually original tail list L = [1,2,3,4]; after op, new tail = [2,3,4,1] (first element removed, and that element appended at the end). That's exactly a rotation left by one (pop front, push back). So after max is at front, the process just rotates the rest of the deque (the n-1 elements) by one position to the left each operation.
But careful: Before the max reaches front, the process is not periodic? However, we can simulate first few steps until the max becomes front (i.e., until the maximum element works its way to the front). Since n <= 1e5, we can simulate these steps explicitly (the number of steps needed is at most something like n? Actually to bring max to front, worst case? Consider initial order: max at last position? e.g., [1,2,3,..., max]. How many steps to bring max to front? Let's simulate: With the process, the front element is always the current max among the first two? Actually known from similar problems: after at most n-1 steps, the maximum element becomes the first. Let's test: initial [1,2,3,4,5], after 4 steps, max is front. If max initially at position i (1-indexed), it will become front after i-1 steps? In example, max at position5, needed 4 steps to become front. Generally, each step, the front element is compared with second; if front is not the max, it will lose to a larger element and that larger element becomes front. So the front is replaced by the maximum of the first two; as the process continues, the max propagates forward. More precisely, the process is equivalent to: we have a queue, we take first two, winner to front, loser to back. This is similar to the "card game" where the maximum eventually ends up at front after n-1 comparisons. Indeed, known from CF problem "A. Queue" (or "A. Cards") that after the first n operations, the array becomes stable with max at front and the rest rotating. Actually typical: first (n-1) steps bring max to front, then cycle length n-1.
Let's analyze formally: Consider operation: take first two x, y. After operation, the first element becomes max(x, y). So the first element after operation is the larger of the two. Thus, the first element is non-decreasing? Actually it becomes at least as large as before? If x is the first, and y is second, after operation first = max(x,y). So first element can increase. The maximum element of the whole deque will eventually become first because whenever it is in the deque and not first, eventually it will get compared to the front when it becomes second. Since each step moves the front and second around, the maximum will move towards the front. It's known that after at most n-1 operations, the first element is the global maximum. Indeed, think of the maximum's index: initially at some position p (0-indexed). In each operation, if the maximum is not at front, then its distance to front reduces by 1? Let's see: Operation: remove first two; then we push either front and back. The positions of other elements shift. Could the maximum's distance increase? Possibly, if it's not in first two, its index might change. But there is classic result: after at most n steps, the maximum bubbles to the front and then stays. Since n is only 1e5, we can simulate until that point (or until we have performed enough steps to answer queries). However, queries m can be up to 1e18, so we cannot simulate beyond maybe n steps. So we need to handle large m by using periodicity after the max is at front.
Thus plan:
Simulate the process step by step, recording for each step t (starting from 1) the pair (A_t, B_t) (the two elements taken at step t) as long as the maximum has not yet become the first element? Actually we need to be able to answer for any m. We can simulate until the first element becomes equal to the maximum element (global max). At that moment, we have reached a "steady state" where first element is fixed and tail rotates.
But careful: Could the maximum become first earlier? Yes. But also there might be some pattern before that. We'll simulate first K steps where K is maybe up to n (or a bit more) until the maximum is at front and also we have seen that the process is periodic from that point onward.
However, we also need to consider if there are duplicate values? Values can be up to 1e9, not necessarily distinct? The problem statement doesn't say distinct. So there could be multiple elements equal to the maximum. In that case, which one becomes the stable front? The process might have the first occurrence of max? But due to ties (A <= B case when equal), if A == B, then condition is else branch (since A > B false). So if equal, we treat A <= B, so B goes to front, A to back. That means if the two are equal, the second becomes front and the first goes to back. So if there are multiple equal maximum values, the front might change even if it's max? Actually if front is max and second is also max (equal), then since A <= B, we put B to front and A to back. So the front changes to the other max (the second) and the previous front goes to back. So the maximum element may not be fixed at front if there are duplicates of the max. Let's test: n=2, both equal, say [5,5]. Step1: A=5,B=5 -> A <= B, so we put B (5) to front, A to back => deque becomes [5,5] again (since push front 5, push back 5, and after removal we had empty? Actually with n=2, initial [5,5]; remove first two, deque empty; then push front B=5, push back A=5 => [5,5]. So it's stable? Actually after step, the deque is [5,5] again, same state. So for n=2, the front remains 5? But which 5? They are equal so it doesn't matter. For larger n, consider [5,5,1]. Step1: A=5,B=5 -> equal, so we put B to front, A to back => new deque: push front 5, then after removal we have [1] (since we removed 5 and 5, left [1]), then push back 5 => [5,1,5]. So front is 5 (the B), and the other 5 moved to back. So still front is max (5). But could the front ever become not a max? Suppose we have max value M. Since M is maximum, any element compared to a non-M will be larger, so if front is M, it will stay M because if compared to a smaller element, condition A > B holds, and we push M to front. If compared to another M (equal), condition A <= B => B (which is also M) goes to front, so front remains M (though possibly a different M). So the front always remains a maximum value (some element with value = global max). So after the front becomes some maximum, it stays a maximum forever (value M). However, the specific element (if distinct indices but same value) might rotate among the max-valued elements? But since values can be equal, we care about the actual numbers A and B for output, i.e., the values. So if there are multiple max values, the value is still M, so output numbers could be M and something else. So it's fine: the front will always have value M after it first attains M. So we can treat "maximum" as value.
But there is nuance: If there are multiple max values, could the front ever become non-max after it becomes max? No, as argued.
Thus after some steps, the first element's value becomes the global maximum (max of all a_i). Let's denote M = max(a). The time to reach that state is at most something: it's known that after at most n steps, the first element is M. In fact, we can simulate until we have performed enough steps such that the front is M and we have also possibly stored the history of pairs for the first some steps. Since n <= 1e5, we can simulate up to, say, n (or maybe 2n) steps, storing the pair for each step. For queries with m <= number of simulated steps, we can directly output stored pair. For larger m, we can use periodic behavior.
Now after the maximum is at front, what's the behavior? As we argued, front stays M (value). The rest of the deque (n-1 elements) rotate left by one each operation. But is that always true regardless of duplicates? Consider if there are multiple max values: Suppose front is M, second is also M. Operation: A=M, B=M (equal). Since A <= B, we push B to front (M) and A to back (M). So after operation, front is still M. The rest: After removal of first two, we have the tail (positions 2..n-1). Then we push front M (the B), and push back A (M). So net effect: The deque becomes: front M, then the previous tail (positions 2..n-1) unchanged? Wait we need to examine carefully.
Let's denote deque after some step where front is M, and the rest is some sequence S of length n-1 (maybe containing other M's). Operation: Remove A = front = M, B = second = first element of S (call it x). After removal, remaining deque is rest of S (size n-2). Then:
If M > x (strictly), then push front M, push back x => new deque: M, (rest of S), x. So new tail = (rest of S) + [x] i.e., S rotated left by one (pop first element, push it to back).
If M == x, then push front B (= M) (which is x, but x = M) and push back A (= M). So new deque: M (the B, which is also M), (rest of S), M (the A). So tail becomes (rest of S) followed by M. So essentially the first element of S (which was M) is moved to back. So again, tail becomes (rest of S) + [first of S] (which is M). So it's also a left rotation by one. So in both cases, the tail (n-1 elements) rotates left by one each operation. Because the second element (B) goes to back if A > B; if equal, B goes to front? Wait we need to confirm: In equal case, B goes to front, A goes to back. So the new deque: front = B (which was second, and equals M). The element that was front (A) goes to back. So the net effect on the sequence of the n-1 tail elements (including the second and the rest) is: The original tail S = [x, rest], where x = second element. After operation, the new tail is: after pushing front B? Actually let's construct:
Initial deque: [A, x, rest...] where A=M, x = S[0], rest = S[1..].
Remove first two: remaining = rest.
If A == x:
Write B (= x) to beginning => push front x.
Write A to end => push back A.
So new deque = [x] + rest + [A] = [M, rest..., M].
So the order of elements in the tail (excluding front) is: rest..., then A (which is M). So it's not exactly the same as rotating S? S = [x, rest...] = [M, rest...]. After rotation left by one (pop front and push to back) would yield: rest..., M. So yes, the new tail (after the front) is rest... then M, which is exactly S rotated left: take first element off and append to end. So indeed, regardless of comparison, as long as A is the front (M) and we compare with B, the operation results in: new front = M (since either A or B is M, but both are M in equality case? Actually if A > B, new front = A = M. If A == B, new front = B = M. So new front always M). And the tail becomes: the previous tail without its first element, then the first element of tail (which was B if A > B, but B is the first element of tail; in equality case, B is also first element of tail) is moved to back? Wait careful: The element that goes to back is: if A > B, then B goes to back; if A <= B, then A goes to back. In both cases, the element that goes to back is the smaller (or equal) of A and B. Since A = M, and B = x, if M > x, B (x) goes to back. So the back gets x. If M == x, then A (M) goes to back. So which element goes to back? In equality, it's the original front A (which is M) that goes to back; the second (also M) becomes front. So the back receives the original front (which is M). So the tail after operation: we have the rest of the tail (excluding the second? Actually we removed both A and B, so the rest = S[1..] (i.e., tail after removing its first element). Then we append the "loser" to the back. So the new tail is: rest (S[1..]) + loser. The loser is either B (if M > B) or A (if M == B). In both cases, the loser is the element that was originally at position 1 (second overall) when M > B, or at position 0 (front) when M == B. So effectively, the new tail is: the old tail S with its first element removed, and then either the old second element (if M > x) or the old front (if M == x) appended. But note when M == x, S = [M, rest...]; after operation, we append A (M) to back, which is same as the old front (also M). But the old front is not part of S (since S is tail of length n-1 including the second and onward). So the element we append (A) is not from S; it's the original front which is not part of S. That means the composition of the tail changes: the tail loses its first element x (which is M) and gains a new M at the end (the original front). So the multiset remains same but the order differs: the new tail is rest... + M (the front). Whereas the old tail was [M, rest...]. So it's exactly a left rotation of the old tail if we consider the old tail as the list of length n-1 that includes the second element onward. But note the old front is not part of the old tail. However, the new tail consists of rest... (which is old tail[1..]) + (the old front). But the old front is M. So the new tail is: old tail[1..] + [M]. That is not a rotation of old tail because old tail included an M at the start, and the new tail includes an M at the end. Since both Ms are identical in value (but maybe different indices but we only care values), it is effectively the same multiset. But is the ordering exactly the same as rotating the old tail left? Let's define T = old tail = [t1, t2, ..., t_{n-1}], where t1 = second element, t2.. are the rest. In the M > t1 case, new tail = [t2, t3, ..., t_{n-1}, t1]. That's a left rotation of T. In the M == t1 case, new tail = [t2, t3, ..., t_{n-1}, M] but note t1 = M, so new tail = [t2, ..., t_{n-1}, M]. That's also [t2, ..., t_{n-1}, t1] because t1 = M. So indeed new tail = [t2, t3, ..., t_{n-1}, t1]! Because t1 is M. So it's the same as left rotation of T. Because the loser in both cases is t1 (the second element) when M > t1? Actually if M > t1, loser = t1; if M == t1, loser? According to rule, when A==B, the loser is A (the front) goes to back, but t1 is B and is not the loser. However we earlier computed new tail = rest + A, not t1. Let's double-check with actual values when M == t1.
Case: A=M, B=M (t1=M). Remove A and B, leaving rest = T[1..] = [t2,...,t_{n-1}]. According to rule: else (A <= B) => write B to beginning, A to end. So we push front B (which is M) and push back A (which is M). So new deque = [B] + rest + [A] = [M] + rest + [M]. So the tail after the front (the new front is B = M) is: rest + [A] = [t2,...,t_{n-1}, M]. But t1 = M. So the new tail is [t2,...,t_{n-1}, M] whereas old tail T = [M, t2,...,t_{n-1}]. Are these the same as left rotation of T? Left rotation of T would be: [t2,...,t_{n-1}, M]. Yes! Because left rotation takes first element and moves to end: T rotated left = [t2,...,t_{n-1}, t1] = [t2,...,t_{n-1}, M]. So indeed it matches. Wait, but is it exactly left rotation? In the operation, we removed A and B; B (t1) becomes front; A (M) goes to back; we didn't put t1 to back, we put A to back. However, since t1 = A = M (same value), it's equivalent. But careful: if t1 is also M but maybe from a different original index, but as value it's M. For the purpose of values in the deque, we don't care about identity; it's just the value M. So the new tail after front is [rest..., M] which is exactly T rotated left. So the behavior is consistent: after max is at front, each step rotates the tail (the n-1 elements) left by one.
Thus after the point where the front becomes M (the maximum value), the sequence of pairs (A, B) for each subsequent step is: A = M (always), and B = the element at the second position. Since the tail rotates left, the second position cycles through the elements of the tail in order. Initially, right after the step when front becomes M, we have some tail configuration (call it initial tail list T0 of length n-1). Then for step k (starting from step number t0+1, where t0 is the step count that brought M to front), the second element is T0[ (k-1) mod (n-1) ]? Let's define:
Let step index s (starting from 1). Let s0 be the first step after which the front becomes M? Actually careful: The condition "front becomes M" may happen after performing some operation? The front after an operation is M. Then for the next operation, the front is M. So the steps where front is M include steps after that operation. In example: after step4 (which produced state4 [5,1,2,3,4]), the front is M. So step5 (the next operation) uses A=5,B=1. So step5 is the first operation where A=M. So we can define s_start as the first step where A = M. That step number can be computed as: after we have simulated until we see front = M at the beginning of a step. In example: at step5, front=5, so step5's A=5. Actually step4's A was 4? Wait: step4: before step4, state3 = [4,5,1,2,3] so A=4, B=5. After step4, we get state4 = [5,1,2,3,4]. So at beginning of step5, state4 has front=5, so A=5. So step5 is first with A=M. So s_start = step number when the front at beginning is M.
Thus for steps s < s_start, we have to simulate and record pairs. For steps s >= s_start, we have A = M always. And B = the ((s - s_start) mod (n-1))-th element of some list L (the tail at the start of step s_start). But careful: At step s_start, the tail (positions 1..n-1) is some list T0. Then step s_start uses A=M, B = T0[0]. After performing step s_start, the tail rotates left, so at beginning of step s_start+1, the tail is T1 = rotate_left(T0). Then step s_start+1 uses B = T1[0] = T0[1] (if n-1 >1). So indeed, for step s_start + k (with k from 0 to (n-2)), B = T0[k] (0-indexed). For step s_start + (n-1), the tail after (n-1) steps returns to T0, so B = T0[0] again. So period = n-1.
Thus overall, for any step m, if m < s_start, we answer from precomputed list. If m >= s_start, we compute index = (m - s_start) mod (n-1). Then B = T0[index]. A = M.
But we must be careful: Is s_start guaranteed to be <= n? Possibly yes: after at most n-1 steps, the maximum reaches the front? Let's test edge cases: n=2, values [0,1] (max 1 at second). Simulate:
Step1: A=0,B=1 -> 0<=1 so push front 1, push back 0 => deque [1,0]. Now front is max M=1. So s_start = step2? Actually step1 used A=0,B=1; after step1 front becomes 1. So at beginning of step2, front=1, so step2's A=1. So s_start=2? But step2 is the first with A=M? Wait step1 had A=0, step2 has A=1. So s_start=2. That's <= n? n=2, s_start=2. Could s_start be > n? Let's try n=5, values [5,1,2,3,4] initially (max already front). Then at step1, front is already 5. So s_start = 1? Actually step1 uses A=5. So s_start=1. That's fine.
Consider case where max appears multiple times? Example: n=3, values [2,2,1] (max=2). Initially front=2, so s_start=1. So it's early. Could max not reach front until later? If max is at position k, then number of steps to bring it to front is at most k-1? Let's simulate: [1,3,2]: step1: A=1,B=3 -> 1<3 => push front 3, push back 1 => [3,2,1]; front is max, so s_start=2? Actually step1 used A=1,B=3; step2 uses A=3. So s_start=2, which is position-1? Initially max at position2 (0-indexed 1? Actually 1-indexed: [1,3,2] -> max at index 2; after 1 step it's front. So indeed s_start = index_of_max? Possibly s_start = index_of_max? Not exactly: if max at index i (1-indexed), then after i-1 steps it becomes front. But careful: step numbers: before any step, deque initial. After step 1, we have performed operation on initial deque. The front after step 1 is? Let's define: We want step t where at beginning front = max. For i=1 (max at front initially), step1's A = max, so s_start=1. For i=2 (max is second), step1's A is not max (first element), but after step1, the max becomes front. So step2's A = max, so s_start=2 = i? For i=3 (max third), step1: A=first, B=second; whichever wins becomes front. The max at third is not yet front. After step1, the max moves to position2? Actually we need to simulate. Take [a,b,c] with c being max. Step1: compare a,b -> winner front, loser back. Suppose a<b => new deque = [b, c, a] (since after removal we had [c], push front b, push back a). Now front is b (which is not max if b<c). The max c is at second position. Step2: compare b and c -> since b<c, we push c to front, b to back => new deque = [c, a, b]. So after step2, front is c. So step3's A = c. So s_start=3 = i. So indeed s_start equals the initial index of the maximum? For i=1: s_start=1; i=2: s_start=2; i=3: s_start=3. Could it be that if there are multiple max values, the first occurrence? Let's test [2,2,1] max at index1, s_start=1. [1,2,2] max at index2 and index3? Actually max=2. Initial [1,2,2]: step1: A=1,B=2 => 1<2 => new [2,2,1] (front 2). So after step1, front is max. So step2's A = max. So s_start=2, which is the first index of max? The first max is at index2 (1-indexed). So s_start = index of first occurrence of maximum? Possibly. In general, the process brings the first occurrence? Let's test [2,1,2] max at positions1 and3. Initial front is max (2). So s_start=1. So it's the index of the first element that is max and eventually stays? But if max appears later, the first max (by order) will eventually become front? Possibly the max that ends up being front is the one that appears earliest among those that are max? Let's try [3,1,3]? Actually values: [1,3,3]? Wait [1,3,3] max at index2,3. Step1: A=1,B=3 => 1<3 => new [3,3,1]; front=3 (max). So s_start=2? Actually step1 used A=1, step2 uses A=3. So s_start=2. So index of first max is 2, s_start=2. If initial [3,1,3], max at index1 and3. front already max, s_start=1. So indeed s_start = position of the first maximum element (1-indexed). Because the maximum elements after it will get overtaken? Let's reason: The process always keeps the first element as the current "champion". If the champion is a max, it stays. If it's not a max, it will eventually lose to a max when that max reaches the front. The first time a max appears at the front, it's after the first max in the order has traveled to the front. Since if there are multiple maxes, the one that appears earlier in the deque will be the first to reach front. So s_start = the index (1-indexed) of the first occurrence of the maximum value. But we must verify: In example [2,1,2], first max at index1, s_start=1. In [1,2,2], first max at index2, s_start=2. In [2,2,1], first max at index1, s_start=1. So that seems plausible. Let's test a more complex: n=5, values [4,5,3,5,2]. Maximum=5. First occurrence of 5 is at index2. So s_start should be 2? Let's simulate quickly: initial [4,5,3,5,2]
Step1: A=4,B=5 -> 4<5 => new: push front 5, push back 4 => [5,3,5,2,4] (since after removal we have [3,5,2], push front 5, push back 4 => [5,3,5,2,4])
Now front =5 (max). So step2's A=5. So s_start=2 indeed matches first occurrence index (2). So yes.
Thus s_start = first index (1-indexed) of maximum value in the initial deque. But wait, is it always exactly equal to that index? Let's test scenario where first element is not max but second is max, we got s_start=2. If third is max and first two are not max, we saw s_start=3. If max at position 4? For n=5, initial [1,2,3,5,4]. First max index=4. Simulate:
Step1: [1,2,3,5,4] -> 1<2 => [2,3,5,4,1]
Step2: [2,3,5,4,1] -> 2<3 => [3,5,4,1,2]
Step3: [3,5,4,1,2] -> 3<5 => [5,4,1,2,3] -> front=5. So after step3, front=5. Step4's A=5. So s_start=4? Actually step4 is first with A=5? Wait step3 used A=3,B=5; after step3 we get front=5. So step4's A=5. So s_start = 4, which equals index of max (4). So consistent.
Thus we can compute s_start as the 1-indexed position of the first maximum element. However, we must be careful: after some steps, the maximum at front might be not the first occurrence? But for our purpose, we only need to know when the front becomes M and what the tail is at that moment. This can be determined by simulating until that point (which is at most n steps). Since n is 1e5, we can simulate step by step until the front becomes M. That's safe even if s_start > n? But s_start <= n obviously. So we can simulate at most n steps to reach that state.
But is there any scenario where the front never becomes M? That cannot happen because max is present and will eventually become front as argued. So after at most n steps, we will have M at front.
Now after we have M at front, we need the tail T0 at that moment (i.e., the sequence of the other n-1 elements in order). This tail can be obtained by simulation as well. Then for any query m, if m <= number of simulated steps (which we can set to up to s_start-1? Actually we need to record pairs for steps up to s_start-1? For m = s_start, we could also compute via formula. But we can simply simulate up to some number L (maybe up to n) and store pairs for all steps from 1 to L. But note q up to 3e5, m up to 1e18, so storing all pairs up to n (1e5) is fine. So we can simulate for steps 1..n (or maybe up to s_start + (n-1) just to be safe? Actually we only need to simulate until we have captured the state where front is M and the tail. That is within n steps. After that we can use periodicity. However, we must be careful: is it guaranteed that after M becomes front, the tail's rotation pattern holds from that exact point onward? Yes, as argued.
But there is a nuance: The process before M becomes front may involve the maximum moving forward and some other operations. However, after M becomes front, the tail T0 at that moment might not be simply the original deque with the max removed and the rest in some order? It will be some permutation. We need to know T0 exactly. So we need to simulate exactly until the beginning of step s_start (i.e., when front = M). At that moment, the deque state is known. Then T0 is the list of elements from index 1 to n-1 (0-indexed). Then we can compute for any m >= s_start: index = (m - s_start) mod (n-1), and B = T0[index]. A = M.
But we also need to consider that for m exactly equal to s_start, this formula works: index = 0, B = T0[0], which is correct.
Now what about the case when n=1? But n>=2 as per constraints, so fine.
Now we must handle queries when n=2 specially? Since n-1 =1, period 1. Then T0 has length 1. For any m >= s_start, B = T0[0] always. So it's constant. That's fine.
Now, is there any scenario where the process becomes periodic earlier than s_start? Possibly not needed.
Implementation Plan:
Read n, q.
Read array a (list of n integers).
Determine global max value M = max(a).
We will simulate the process step by step using a data structure that allows efficient removal of first two and insertion at front and back. But n up to 1e5, and we only need to simulate up to s_start (which is at most n). Actually we need to simulate until we have reached the state where front = M at beginning of a step. But s_start could be up to n. So we need to simulate at most n operations. Each operation involves O(1) if we use a deque (double-ended queue) from standard library. Python's collections.deque supports popleft, appendleft, append, etc. So we can simulate n steps, which is 1e5, fine. However, we need to store for each step the pair (A,B) for steps 1..(s_start-1)? Actually we need to answer queries for any m. For m <= s_start-1 we can answer directly from simulation; for m >= s_start we use formula. So we need to know the pair for steps up to s_start-1? But we may also need step s_start if query m = s_start; but that also can be answered by formula. But to be safe, we can simulate until we have performed step s_start? Actually we need to know the state at the beginning of step s_start (i.e., before performing operation s_start). That state is after step s_start-1. So we can simulate step by step, and after each step, we can check the new front. However, we also need to record the pairs for each step as we simulate. So we can simulate for step = 1 to maybe up to n (or up to when we have gathered enough info). Let's decide: We'll simulate while we haven't yet reached the point where the front is M at the start of a step? Actually we need to detect when we are about to perform an operation and the front is M. That is the condition for step t. So we can simulate as follows:
Initialize deque d with a.
We'll maintain a list history = [] of tuples (A,B) for steps performed.
We'll also maintain a variable step = 1.
We'll loop while step <= n? But we might need to go until front becomes M. However, it's possible that front becomes M after some operation, but we need to know the tail at the start of the first operation where front is M. So we can simulate until the front (d[0]) equals M. At that moment, we have not yet performed the operation for that step. So we are at the beginning of step step (with step = some number). So we can set s_start = step. And we also need to capture the current deque state (which is after step-1 operations) to extract T0. So we can break out of simulation at that point (since we don't need to simulate further). However, we still may need to answer queries with m < s_start, which we would have recorded during simulation up to step-1. So we need to simulate step by step until we either have performed s_start-1 operations, or we reach front=M before performing an operation? Actually we want to stop before performing the operation where front is M. Let's design:
We'll do:
d = deque(a)
step = 1
history = dict or list indexed by step number (1-indexed) to store (A,B). We'll simulate while True:
if d[0] == M:
# this is the start of a step where front is M
# record that this step number is s_start
s_start = step
# capture current state: tail = list(d)[1:] (n-1 elements)
tail = list(d)[1:] # but careful: d may have length n? It should still be n.
break
else perform operation for current step
A = d.popleft()
B = d.popleft()
history[step] = (A,B)
if A > B:
d.appendleft(A)
d.append(B)
else:
d.appendleft(B)
d.append(A)
step += 1
But we need to also handle the case when initially d[0] == M (i.e., s_start = 1). Then we break immediately without performing any operation; history for step 1 is not recorded yet. But for queries m=1, we need to output (A,B) = (M, second). So we still need to know the pair for step 1. In that case, we should not break before performing; instead we need to treat step 1 as s_start. So we could adjust: we check after we have determined that we are at a step where front == M. If step == 1, then s_start = 1. But we still need to have the ability to answer queries for m=1 using formula (since it's periodic). So we can set s_start = 1 and capture tail from initial deque. Then we don't need to simulate any operations for the periodic part. However, we might also want to record history for steps before s_start? There are none. So fine.
If step > 1, we have already recorded history for steps 1..(s_start-1). Good.
Now after breaking (or if initially front == M), we have s_start, and tail T0 (the list of length n-1). Also we know M.
But note: after we break, we have not performed the operation for step s_start. That's fine because for steps >= s_start we will use formula.
Now we need to answer queries. For each query m:
if m < s_start: output history[m]
else:
idx = (m - s_start) % (n-1)
A = M
B = tail[idx] # tail is list of length n-1
print(A, B)
But we must ensure that tail is captured correctly. In the case s_start = 1, tail is initial deque[1:]. In the case s_start > 1, tail is the state after performing s_start-1 operations (i.e., the deque at the beginning of step s_start). That's exactly what we captured.
Now we need to verify with example:
Example1: n=5, a=[1,2,3,4,5], M=5, first occurrence of 5 is index5? Actually a: [1,2,3,4,5] => first max at index5. So s_start = 5? But from simulation earlier we thought s_start=5? Actually we computed from example: step5 is first where A=5. That matches index=5. So s_start=5. Let's simulate with our algorithm:
Initial d = [1,2,3,4,5], M=5, d[0]=1 != M, so we perform step1:
A=1,B=2 => history[1]=(1,2); after op: push front max? Since 1<2 => push front 2, push back 1 => d=[2,3,4,5,1]
step=2; d[0]=2 != M => perform step2: A=2,B=3 => (2,3); op: push front 3, push back 2 => d=[3,4,5,1,2]
step=3; d[0]=3 != M => step3: (3,4); d=[4,5,1,2,3]
step=4; d[0]=4 != M => step4: (4,5); after op: A=4,B=5 => 4<5 => push front 5, push back 4 => d=[5,1,2,3,4]
step=5; now d[0]=5 == M => break. s_start=5, tail = list(d)[1:] = [1,2,3,4].
Now we need to consider edge cases: n=2. Example: n=2, a=[0,1]. M=1, first occurrence index2? Actually a=[0,1] => first max at index2. So s_start=2? Let's test simulation:
Initial d=[0,1]; d[0]=0 != M -> step1: A=0,B=1 => history[1]=(0,1); op: 0<1 => push front 1, push back 0 => d=[1,0]
step=2; d[0]=1 == M => break. s_start=2, tail = [0] (n-1=1).
Now queries: m=1 -> history[1]=(0,1) correct.
m=2 -> m>=2: idx = (2-2)%1 =0, tail[0]=0, A=1 => (1,0). What should step2 be? At step2, before operation, deque is [1,0], so A=1,B=0 => (1,0). Correct.
m=3 -> idx = (3-2)%1=0 => (1,0). Indeed after step2, deque? Let's simulate: after step2, operation would be performed: A=1,B=0 => 1>0 => push front 1, push back 0 => d=[1,0] again. So step3's A,B = (1,0). So correct.
Now consider case where M appears at front initially: n=5, a=[5,1,2,3,4]. M=5, first occurrence index1 => s_start=1. Our algorithm: initial d[0]=5 == M => break immediately with s_start=1, tail = [1,2,3,4]. Then for m=1: m>=1, idx = (1-1)%4=0, tail[0]=1 => (5,1). That's correct: step1 should be A=5,B=1. For m=2: idx = (2-1)%4=1 => tail[1]=2 => (5,2). Check simulation: step1 operation: A=5,B=1 => 5>1 => push front 5, push back 1 => d=[5,2,3,4,1]. Step2's A=5,B=2 => (5,2). So matches.
Now consider duplicates: n=5, a=[2,2,1,3,2]. Max=3, first occurrence index4? Actually array: [2,2,1,3,2] => max=3 at index4 (1-indexed). So s_start=4. Simulation should confirm. Let's simulate quickly:
d0=[2,2,1,3,2], M=3, d[0]=2 !=3 => step1: A=2,B=2 => (2,2); op: equal => push front 2, push back 2 => d=[2,1,3,2,2]? Actually removal: after removing first two, remaining [1,3,2]; push front B=2, push back A=2 => d=[2,1,3,2,2].
step2: d[0]=2 !=3 => A=2,B=1 => (2,1); 2>1 => push front 2, push back 1 => d=[2,3,2,2,1]? Remove 2,1, remaining [3,2,2]; push front A=2? Wait A=2, B=1, A>B so push front A=2, push back B=1 => d=[2,3,2,2,1]? Actually after removal we have [3,2,2]; then push front 2, so front becomes 2, then list: [2,3,2,2], then push back 1 => [2,3,2,2,1]. Yes.
step3: d[0]=2 !=3 => A=2,B=3 => (2,3); 2<3 => push front 3, push back 2 => d=[3,2,2,1,2]? Remove 2,3, remaining [2,2,1]; push front B=3, push back A=2 => d=[3,2,2,1,2].
step4: now d[0]=3 == M => break. s_start=4, tail = list(d)[1:] = [2,2,1,2]. So tail length 4.
Now m=4: idx=0 => B=2, A=3 => (3,2). Indeed step4 should be A=3,B=2. That's correct.
Now m=5: idx=1 => B=2 => (3,2). Check: after step4 operation (which we haven't performed yet), the deque would become? Actually step4 we haven't performed. But our model says for m>=4, we compute using tail. So step4: (3,2). step5: tail index1 => 2 again? Actually tail = [2,2,1,2] so index1 is 2. So step5: (3,2). Let's manually simulate step4 and step5 to verify:
Start of step4: d=[3,2,2,1,2] (as above). Operation step4: A=3,B=2, since 3>2 => push front 3, push back 2 => after removal, remaining [2,1,2]; push front 3, push back 2 => d=[3,2,1,2,2].
Now start of step5: d=[3,2,1,2,2]; A=3,B=2 => (3,2). So yes step5 yields (3,2). So B=2 (the second element is 2). In tail, index1 = 2, matches. So periodic pattern holds.
Now what about if tail contains M values? That's fine as we saw. The rotation pattern still holds.
Now need to consider n=2 and duplicates: a=[5,5]. M=5, first occurrence index1 => s_start=1? Actually first max at index1. So s_start=1, tail = [5]. Then m=1: (5,5). m=2: (5,5). Indeed step1: A=5,B=5 => (5,5); after op, deque remains [5,5]; step2: (5,5). So formula: for m>=1, idx = (m-1)%1=0, tail[0]=5 => (5,5) correct.
Thus solution appears correct.
But we must be careful: The process may not have reached periodic state exactly at s_start if n-1 = 0? n >=2, so n-1 >=1.
Now we need to handle q=0 (no queries). Output nothing.
Now complexity: Simulating up to s_start steps (max n) using deque, O(n). Storing history for up to n steps, O(n). Answering queries O(q) each O(1). q up to 3e5, fine.
Now we must also consider potential pitfalls: We are breaking when d[0]==M before performing that step. But what if we never encounter d[0]==M? That would only happen if we have performed all n steps and still front not M? But we argued after at most n steps, front should be M. However, we might have a situation where after performing n steps, we haven't broken because we always performed operations and didn't check after each operation? Actually we check at beginning of each step. After performing step i, we increment step and then loop again. So if we simulate up to step = n (or more), we will eventually have step = n+1? But we must bound simulation. Since s_start <= n, we will break before step exceeds n+1? Actually if first max index is n, s_start = n. Our loop: step starts at 1, we check d[0]==M. If not, we perform operation, then step++. After performing step (n-1) operation, step becomes n. At beginning of step n, we check d[0]. Should be M. So break. So maximum operations performed in simulation = n-1. So that's fine.
But what if first max index is n and we have n=100000, we simulate 99999 operations, which is okay. So algorithm is O(n).
Now we must implement carefully with deque in Python.
But there is one nuance: The deque size is n, and we are using popleft twice and then appendleft/append. That is fine.
Now we need to store history. Since we may need to answer m < s_start, which are at most n-1, we can store a list of tuples of length maybe n. Use 1-indexed: history = [None] * (n+1) or just a dict.
Now we also need to compute tail after breaking. That is list(d)[1:]. However, converting deque to list is O(n), which is okay since we do it once. n=1e5.
Now check large m: (m - s_start) mod (n-1) may be large, but Python handles big ints.
Now confirm that the periodic pattern indeed holds for all m >= s_start, even when there are multiple max values. As argued, after max is at front, each step rotates tail left, so second element cycles through tail. So it's correct.
Now we must also consider if after some steps before reaching s_start, the process might already become periodic with a different period? Not needed.
Now we need to ensure that the first maximum element indeed ends up being the front. But what about case when there are multiple max values and the first max is not the one that ends up front? Let's try to construct a counterexample. Suppose initial: [2, 1, 2] (max=2). First max at index1, so front already 2, so s_start=1. That's fine.
Suppose initial: [1,2,2,1]. max=2, first max at index2. We expect s_start=2. Let's simulate:
d0=[1,2,2,1]; step1: A=1,B=2 -> 1<2 => push front 2, push back 1 => d=[2,2,1,1]? Actually after removal we have [2,1]; push front 2, push back 1 => [2,2,1,1]? Wait careful: initial n=4. Remove first two (1,2) -> remaining [2,1]; push front B=2, push back A=1 => new deque: front 2, then [2,1] (from remaining), then back 1 => [2,2,1,1]. Yes.
Now front=2 (max) at start of step2. So s_start=2 indeed. The tail = [2,1,1]. So tail includes a max value (2). Step2: A=2, B=2 (since tail[0]=2) -> equal => operation: push front B=2, push back A=2 => after removal we have [1,1]; push front 2, push back 2 => [2,1,1,2]. tail becomes [1,1,2]. Step3: A=2,B=1 => (2,1). So B cycles. The tail rotates left: original tail [2,1,1] -> after step2 becomes [1,1,2] which is indeed left rotation of [2,1,1]? Rotating left: [2,1,1] -> [1,1,2] yes. So pattern holds.
What if initial: [3,1,3,2]? max=3, first max at index1, so s_start=1.
Thus seems consistent.
Now, we must also think about correctness when n=1? Not allowed.
Now let's test more random cases with a brute-force simulation for small n and random values to confirm our formula. We'll later do mental or maybe write a quick test in mind.
But there is one more nuance: The process described in problem statement: "He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque." This is exactly as we implemented.
Now we also need to be careful with indexing: The queries ask for "which two elements he will pull out on the m_j-th operation". That is A and B at the start of the m-th operation. So our approach matches.
Now confirm with given second example: n=2, q=0, no output. That's fine.
Now we should also consider potential overflow or performance issues: q up to 3e5, each query answer is just two numbers. Memory fine.
Now one more corner: n=2, s_start can be 1 or 2. Already handled.
Now, what about n=2 and s_start=2? Already handled.
Now test: n=2, a=[5,3]. M=5, first max index1 => s_start=1. tail=[3]. Queries: m=1 -> (5,3). m=2 -> (5,3)? Let's simulate: step1: A=5,B=3 => 5>3 => push front 5, push back 3 => deque [5,3]. So step2: A=5,B=3 => (5,3). So yes.
Now test: n=3, a=[2,1,3] => M=3 first max index3 => s_start=3? Let's simulate:
d0=[2,1,3] step1: A=2,B=1 => 2>1 => push front 2, push back 1 => d=[2,3,1]? Actually after removal we have [3]; push front 2, push back 1 => [2,3,1].
step2: d=[2,3,1] => A=2,B=3 => 2<3 => push front 3, push back 2 => d=[3,1,2]
step3: d[0]=3 == M => s_start=3, tail=[1,2]. So m=3: idx=0 => B=1 => (3,1). Let's manually see: step3 operation should be A=3,B=1 => (3,1). Yes. m=4: idx=1 => B=2 => (3,2). After step3 operation: d becomes? step3: A=3,B=1, 3>1 => push front 3, push back 1 => d=[3,2,1]? Actually after removal we had [2]; push front 3, push back 1 => [3,2,1]. So step4: A=3,B=2 => (3,2). Good.
Now test duplicates with max appearing later but also other max earlier? Actually if there is an earlier max, s_start is earlier. So no issue.
Now consider scenario where M appears at front initially, but tail contains M. Then rotation works.
Now verify that our simulation to capture tail works correctly when s_start=1: we break immediately and tail = list(d)[1:]. That's the initial tail. Good.
Now about complexity: For n up to 1e5, we may need to convert deque to list after simulation. That's fine.
Now potential bug: We might break before recording history for step s_start if s_start>1? But we break when we detect at beginning of step that front == M. That means we have not yet performed that step, so history for steps 1..(s_start-1) are recorded. Good.
Now what about the case where the front becomes M exactly after performing an operation, but we would have incremented step and then check at beginning of next step. So detection is at beginning of a step. That's fine.
Now we need to be careful about handling the case when n-1 = 0? Not possible because n>=2.
Now final algorithm steps:
Read n, q.
Read list a of length n.
Compute M = max(a).
Initialize deque d = deque(a).
Initialize step = 1.
Initialize an array history = [None] * (n+1) maybe or use dictionary; but we need to store up to n steps. Since step numbers can be up to n, we can allocate list of size n+1.
While True:
if d[0] == M:
s_start = step
tail = [d[i] for i in range(1, n)] # or list(d)[1:]
break
else:
A = d.popleft()
B = d.popleft()
history[step] = (A, B)
if A > B:
d.appendleft(A)
d.append(B)
else:
d.appendleft(B)
d.append(A)
step += 1
Note: Ensure that we don't exceed step beyond n? But loop will break before that because s_start <= n. However, if due to bug we never break (shouldn't), we might infinite loop. We could add a max_iter = n (or n+5) as safety.
Now after loop, we have s_start, tail (list of length n-1). Also note that step might be > n? Actually step increments after each operation, and we break when d[0]==M. The maximum step value at break is s_start. Since s_start <= n, step = s_start at break. So step not exceeding n.
Now answer queries:
For each m:
if m < s_start:
ans = history[m] # should exist
else:
idx = (m - s_start) % (n-1)
ans = (M, tail[idx])
print ans[0] ans[1]
Now we should test with the given example.
Now we need to think about correctness when n=1? Not allowed.
Now potential issue: Our history array may be of size n+1, but we only fill for steps up to s_start-1. That's fine.
Now about memory: n up to 1e5, history list of tuples of two ints -> fine.
Now consider time: simulation of up to n steps, each step O(1). q up to 3e5.
Now confirm with another random test using brute force for small n. We'll do mental small:
n=3, a=[0,0,1] (max=1 at index3). Sim:
d0=[0,0,1]; step1: d[0]=0 !=1 => A=0,B=0 => (0,0); equal -> push front 0, push back 0 => d=[0,1,0]? Remove 0,0 -> remaining [1]; push front B=0, push back A=0 => [0,1,0].
step2: d[0]=0 !=1 => A=0,B=1 => (0,1); 0<1 -> push front 1, push back 0 => d=[1,0,0]? Remove 0,1 -> remaining [0]; push front B=1, push back A=0 => [1,0,0].
step3: d[0]=1 == M => break. s_start=3, tail=[0,0].
Now queries: m=1 => (0,0); m=2 => (0,1); m=3 => (1,0); m=4 => idx = (4-3)%2 =1 => tail[1]=0 => (1,0). Actually manually: step3 operation: A=1,B=0 => (1,0); after step3 op: d becomes? A=1,B=0, 1>0 -> push front 1, push back 0 -> after removal [0] -> [1,0,0] again? Actually after step3, d = [1,0,0] (same as before). So step4: (1,0). So (1,0) again. tail[0]=0, tail[1]=0, both 0, so (1,0) always. So matches.
Now consider n=3, a=[1,0,0] (max=1 at index1). s_start=1, tail=[0,0]. m=1 => (1,0). m=2 => (1,0). Works.
Now consider n=4, a=[2,1,3,2] (max=3 at index3). s_start? first max at index3 => s_start=3. Let's simulate quickly to see if break happens correctly.
d0=[2,1,3,2] step1: d[0]=2 !=3 => A=2,B=1 => (2,1); 2>1 -> push front 2, push back 1 => d=[2,3,2,1]? Remove 2,1 -> remaining [3,2]; push front 2, push back 1 => [2,3,2,1].
step2: d[0]=2 !=3 => A=2,B=3 => (2,3); 2<3 -> push front 3, push back 2 => d=[3,2,1,2]? Remove 2,3 -> remaining [2,1]; push front 3, push back 2 => [3,2,1,2].
step3: d[0]=3 == M => break. s_start=3, tail=[2,1,2].
Now queries: m=3 => (3,2). m=4 => idx = (4-3)%3=1 => tail[1]=1 => (3,1). Check manually: step3 operation: A=3,B=2 -> 3>2 => push front 3, push back 2 => after removal we have [1,2]? Actually step3 start: d=[3,2,1,2]; remove 3,2 -> remaining [1,2]; push front 3, push back 2 => d=[3,1,2,2]. So step4: A=3,B=1 => (3,1). So matches.
Thus algorithm seems correct.
Now we must confirm that the first maximum index indeed equals s_start. But we didn't rely on that formula; we simulated until detection. That's safer and handles any nuance like multiple maxima etc. Simulating up to n steps is acceptable.
But we need to ensure that after breaking, the tail list we capture is exactly the tail at the beginning of step s_start. Since we broke when d[0]==M, we haven't modified deque yet. So tail is correct.
Now an important nuance: In the process, the number of elements always remains n. So after each operation, deque size remains n.
Now, what about queries with m = 0? m_j >= 1, so no.
Now we need to handle q up to 300k and output efficiently. Use sys.stdout.write.
Now we should also consider that for some test cases, s_start could be large (n) and we need to store history for steps 1..n-1. That's up to 99999 entries, fine.
Now edge case: n=2 and s_start=2. Our simulation will perform step1 and then break at step2. So history[1] stored. tail captured as [d[1]] after step1? Let's confirm: After step1 operation, d = [1,0] in earlier example; then step=2; check d[0]==M? In example [0,1] after step1 d=[1,0]; M=1, d[0]=1 => break. So tail = [0]. That's correct.
Now if n=2 and s_start=1, we break immediately, tail = initial[1] = second element. So history empty.
Now we need to be careful that in the simulation loop, after performing operation, we increment step. So step becomes step+1. Then we go to next iteration and check condition at beginning. That's fine.
Now implement.
Potential performance: Using Python's deque popleft and appendleft is O(1). But converting deque to list each time we capture tail is O(n) once, fine.
Now we also need to consider if the input q is 0, we don't output anything.
Now let's double-check with provided example exactly.
Input:
5 3
1 2 3 4 5
1
2
10
Our algorithm: M=5, s_start=5, tail=[1,2,3,4] (as derived). For m=10: (5,2) as above.
Now test with custom: n=5, a=[5,4,3,2,1]. M=5, s_start=1, tail=[4,3,2,1]. m=1 => (5,4). m=2 => idx=(2-1)%4=1 => tail[1]=3 => (5,3). Simulate: step1: (5,4) -> after op: since 5>4, push front5, push back4 => d=[5,3,2,1,4]. step2: (5,3) correct. So algorithm holds.
Now what about if there are many queries and n=100000, we need to compute modulo efficiently. That's fine.
Now one more nuance: The tail we captured is a list of length n-1. For m >= s_start, we compute index = (m - s_start) % (n-1). However, what if n-1 = 1? Then modulo 1 always 0.
Now we need to ensure that for m exactly s_start, index=0 yields B = tail[0] which is the second element at that moment.
Now confirm with example: n=2, a=[0,1], s_start=2, tail=[0]? Actually from earlier: after step1, d=[1,0]; tail = [0]. For m=2: idx=0, B=0 => (1,0) correct.
Now think about potential off-by-one: The step counting: Our simulation loop: step initialized to 1. While True: check d[0]==M? If yes, set s_start=step, break. Else perform operation for step, record history[step] as (A,B), then step += 1. So step after recording becomes next step number. So at break, step = s_start, and we haven't performed operation for step s_start. So for m = s_start, we need to use periodic formula. That's what we do.
Now what about when s_start=1: step=1, we check d[0]==M, true, so break without performing any operation. So s_start=1, history empty. For m=1, we go to else branch: m>=s_start, compute idx = (1-1)%(n-1)=0, B=tail[0] (which is initial second element). So correct.
Now what about if we had performed some operations and later front becomes M, we break. Suppose s_start=5, we have performed operations for steps 1..4. history[1..4] filled. step=5 at break. So all good.
Now need to verify that we didn't accidentally lose the first element when capturing tail? tail = list(d)[1:] works.
Now implement.
Now consider memory: history list of size n+1 may be large but okay.
Now what about large n and many queries? fine.
Now is there any scenario where the periodic tail length is not n-1? For example, after max becomes front, tail always length n-1. That's consistent.
Now we must ensure that the process indeed always results in max at front by at most n steps. Could there be a scenario where due to ties (multiple max) the front changes but still max? That's fine.
Now but there is a subtlety: Suppose the maximum value appears only once, but there is another value equal to max? That's contradictory; if it appears only once, it's unique. So duplicates are only if multiple.
Now think about whether the process might have a different periodic behavior if the max is not unique and the front could change among max elements? But the front value is always max, so output A = max always for m>=s_start. So that's fine. B may be max sometimes if tail contains max. That's allowed.
Now one more nuance: The periodic behavior might start before the front becomes max? Could it be that after some steps, the front is not max but the process becomes periodic? Possibly if the maximum is not at front but the deque state repeats? But since the front increases until max, and max is unique value? Not necessarily; if there are multiple max, the front might be max earlier. But if max is unique, the front increases strictly until it reaches max, so it cannot cycle before that. So no.
Now we need to make sure that for large m, we compute modulo with (n-1). But what if n=1? Not possible.
Now also note that n can be up to 1e5, but q can be up to 3e5, and m up to 1e18. So we must compute modulo using Python's big ints.
Now we should also handle case where s_start might be > some m, we use history. Since we stored history up to s_start-1, and s_start <= n, it's fine.
Now test for n=100000, random values: simulation of at most 100000 operations is okay. But we need to be careful about time: Python may be okay with 1e5 operations, each deque operation O(1). It's fine.
Now we must also read input efficiently using sys.stdin.read.
Now final step: Write code.
But wait, there is a potential issue: In our simulation, we perform popleft twice. However, after popleft, the deque size reduces to n-2, then we push front and push back, restoring size to n. That's fine.
Now what about the case where n=2 and we popleft both, deque empty, then we push front and push back, restoring size. That's fine.
Now we need to be careful about variable naming to not overshadow built-ins.
Now let's consider a more formal proof: It's similar to known Codeforces problem "B. Interesting drink"? Actually there's a Codeforces problem "A. Lucky Ticket"? No.
I recall problem "C. Little Pony and Sort by Shift"? Not.
But there is a known problem: "A. Queue" from Codeforces Round # 137? Not sure.
Anyway, we have a solution.
Now implement:
Pseudo:
import sys
from collections import deque
def main():
data = sys.stdin.read().split()
it = iter(data)
n = int(next(it))
q = int(next(it))
a = [int(next(it)) for _ in range(n)]
queries = [int(next(it)) for _ in range(q)]
code
M = max(a)
d = deque(a)
step = 1
history = [None] * (n+1) # index by step
# simulate until front is max
while True:
if d[0] == M:
s_start = step
# extract tail
# Convert to list? We can use slicing: list(d)[1:]
tail = [d[i] for i in range(1, n)] # but n known; but if d is deque, indexing may be O(n)? Actually indexing a deque in Python is O(n) worst-case? Wait, collections.deque supports __getitem__ but it's O(n) in the worst case? Let's check: In CPython, deque supports index access, but it's optimized to start from whichever end is closer. However, for arbitrary index, it's O(n) in the worst case? Actually the implementation of deque is a doubly-linked list of blocks. __getitem__ is implemented by iterating from the left or right depending on index; it is O(k) for accessing the kth element, but they claim "Indexed access is O(1) at both ends but slows to O(n) in the middle." Since we are accessing from index 1 up to n-1, it's not O(1) per element? Actually to get all elements, it's O(n) total. So using list(d) is O(n) which is fine. But we can simply do tail = list(d)[1:], which is also O(n). That's acceptable since we do it once. However, we need to be careful about performance: converting deque to list is O(n). That's okay for n=1e5.
# But we can also pop elements to a list? Not necessary.
tail = list(d)[1:] # O(n)
break
# else perform operation
A = d.popleft()
B = d.popleft()
history[step] = (A, B)
if A > B:
d.appendleft(A)
d.append(B)
else:
d.appendleft(B)
d.append(A)
step += 1
# optional safety: if step > n: break (but shouldn't happen)
if step > n: # just in case, break and set s_start = step, tail = list(d)[1:]
# but we trust it will break earlier
out_lines = []
period = n - 1
for m in queries:
if m < s_start:
pair = history[m]
else:
idx = (m - s_start) % period
pair = (M, tail[idx])
out_lines.append(f"{pair[0]} {pair[1]}")
sys.stdout.write("\n".join(out_lines))
if name == "main":
main()
Now we need to consider the case when n is 2 and period = 1. tail length 1, works.
Now think about performance of history list: We store up to n entries, each tuple of two ints. Fine.
Now we should test with an extreme case: n=100000, all values equal to 0. Then M=0, first max at index1, s_start=1, tail = a[1:] (all zeros). So for any m, answer (0,0). That's fine. Simulation would break immediately, no operations performed. So O(1).
Now consider n=100000, values decreasing: [100000, 99999, ...], M=100000 at front, s_start=1. So immediate break.
Now consider worst-case for simulation: maximum at last position, like increasing sequence [1,2,3,...,100000]. Then s_start = n = 100000. Our loop will perform n-1 operations. That's 99999 operations, each O(1). So acceptable. But we also store history for steps 1..n-1, which is 99999 entries. That's fine.
Now what about memory for tail? tail length 99999, list. Acceptable.
Now consider q up to 300k, we answer each in O(1). Good.
Now ensure we handle q=0: then out_lines is empty, sys.stdout.write("") maybe prints nothing, or "\n".join([]) gives '', which is fine.
Now test more random with brute force for small n. Let's manually test n=4, a=[3,1,2,4]. M=4, first max at index4 => s_start=4? Actually array: [3,1,2,4] => first max index4. Simulate:
d0=[3,1,2,4]
step1: d[0]=3 !=4 -> A=3,B=1 -> (3,1); 3>1 -> push front3, push back1 -> d=[3,2,4,1]? remove 3,1 -> remaining [2,4]; push front3, push back1 -> [3,2,4,1]
step2: d[0]=3 !=4 -> A=3,B=2 -> (3,2); 3>2 -> push front3, push back2 -> d=[3,4,1,2]? remove 3,2 -> remaining [4,1]; push front3, push back2 -> [3,4,1,2]
step3: d[0]=3 !=4 -> A=3,B=4 -> (3,4); 3<4 -> push front4, push back3 -> d=[4,1,2,3]? remove 3,4 -> remaining [1,2]; push front4, push back3 -> [4,1,2,3]
step4: d[0]=4 == M -> break. s_start=4, tail=[1,2,3]. So m=4 => (4,1); m=5 => idx=(5-4)%3=1 => tail[1]=2 => (4,2); m=6 => (4,3); m=7 => (4,1) again. Let's manually step:
Step4: A=4,B=1 -> (4,1); after op: 4>1 -> push front4, push back1 -> d=[4,2,3,1]? remove 4,1 -> remaining [2,3]; push front4, push back1 -> [4,2,3,1]; step5: (4,2); after op: 4>2 -> d=[4,3,1,2]; step6: (4,3); after op: 4>3 -> d=[4,1,2,3]; step7: (4,1) matches. So good.
Now test case with duplicates and first max not at front but there are multiple max: a=[2,4,1,4]? Actually max=4, first max index2. Simulate quickly to ensure tail captured correctly.
d0=[2,4,1,4]
step1: d[0]=2 !=4 -> A=2,B=4 -> (2,4); 2<4 -> push front4, push back2 -> d=[4,1,4,2]? remove 2,4 -> remaining [1,4]; push front B=4, push back A=2 -> [4,1,4,2]
step2: d[0]=4 == M -> break. s_start=2, tail=[1,4,2].
Now m=2: (4,1). m=3: idx=(3-2)%3=1 -> tail[1]=4 => (4,4). Let's manual: step2: A=4,B=1 -> (4,1); after op: 4>1 -> push front4, push back1 -> d=[4,4,2,1]? remove 4,1 -> remaining [4,2]; push front4, push back1 -> [4,4,2,1]; step3: A=4,B=4 -> (4,4). So correct. So algorithm works even when B is max.
Now what about scenario where after s_start, the tail includes M and the rotation works, but the period is n-1. That's correct.
Now we need to consider if n-1 = 0? Not possible.
Now one more nuance: In our simulation loop, we used while True, but we must ensure we don't run forever if something goes wrong. We can add a condition if step > n: break and set s_start = step, tail = list(d)[1:]. But we trust the property.
Now important: When we break, we set s_start = step, which is the current step number (the one we haven't performed). But we need to guarantee that step <= n. It holds.
Now about reading input: It says 0 ≤ q ≤ 3e5. So q may be 0. Our code should handle that.
Now we should also test with n=2, a=[5,5]. M=5, s_start=1, tail=[5]. m=1 => (5,5). Good.
Now implement.
But I want to think about potential pitfalls: The problem statement says "He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A > B, he writes A to the beginning and writes B to the end of the deque, otherwise, he writes to the beginning B, and A writes to the end of the deque." This exactly matches our operation.
Now some might think that after operation, the order might be different: For A > B, we write A to beginning (so it becomes new front) and B to the end. For else, we write B to beginning and A to the end. That's consistent.
Now we need to confirm that our simulation correctly models the operation order: After popping A and B, we have the rest of the deque (call it R). Then we push something to front and then push something to back. But order of pushing matters: If we push to front first, then the element we push to back will be after all existing elements. In our code: after popping, we do if A > B: d.appendleft(A) then d.append(B). That yields deque: [A] + R + [B]. In else: d.appendleft(B) then d.append(A) => [B] + R + [A]. That matches the described operation.
Now verify with example: Step1 initial [1,2,3,4,5] -> pop A=1,B=2, R=[3,4,5]; since 1<2, else branch: appendleft(B=2) => [2,3,4,5]; then append(A=1) => [2,3,4,5,1]. That's correct.
Now check when A>B: e.g., step5 from earlier: [5,1,2,3,4] -> pop 5,1, R=[2,3,4]; A>B so appendleft(5) => [5,2,3,4]; then append(1) => [5,2,3,4,1] correct.
Thus code matches.
Now final code.
But I recall that in similar known problems (Codeforces 1579? Actually problem "B. MEX and Array" no), there is an easier solution: The answer for m=1..n-1 are just the first two elements at each step until max becomes first, and after that it's periodic. But we need to compute these first n-1 steps explicitly. However, we may compute them without simulation using the observation that the first n-1 steps correspond to the first n-1 elements of the array after some transformation? But simulation is easier and safe given n=1e5.
Now one more nuance: The problem constraints: 2 ≤ n ≤ 10^5, 0 ≤ q ≤ 3*10^5, m_j up to 10^18. Our solution uses O(n) simulation and O(q) queries. This should pass.
Now we need to watch out for Python's performance: For n=100000, simulation of 100000 operations with deque is fast. But we also convert deque to list (tail) once, which is O(n). So overall O(n) ~ 1e5, fine.
Now consider worst-case where we simulate 99999 operations, each operation does 2 poplefts, and 2 appends (appendleft/append). That's 4 ops per step. So about 400k deque ops, which is trivial.
Now test with random big numbers: a_i up to 1e9, but we just store ints.
Now we need to ensure we use sys.stdin.buffer for faster input.
Now finalize.
But before finalizing, I want to consider if there is any scenario where s_start may be > n? Actually first occurrence index is at most n. So fine.
Now maybe we can compute s_start directly as first index of max, but we use simulation anyway. However, using simulation ensures correctness even if there is some subtlety where the max reaches front earlier than its index? Actually we argued that s_start equals first max index. But is that always true? Let's try a case: n=4, a=[2,3,1,3] max=3, first max at index2. Should s_start be 2? Simulate:
d0=[2,3,1,3] step1: A=2,B=3 => 2<3 => push front3, push back2 => d=[3,1,3,2]? Remove 2,3 -> remaining [1,3]; push front3, push back2 => [3,1,3,2]. Now front=3 at start of step2 => s_start=2. That matches. So yes.
Try a case where the first max is at index3 but it becomes front at step2? For example: a=[1,4,2,3] max=4 first at index2? Actually index2. To get index3, try [1,2,4,3]. First max index3. Simulate: d0=[1,2,4,3] step1: 1<2 => d=[2,4,3,1]; step2: d[0]=2 !=4? Actually after step1, d=[2,4,3,1]; step2: A=2,B=4 => 2<4 => d=[4,3,1,2]; front=4 at start of step3? Actually step2 operation yields d=[4,3,1,2]; so after step2, step=3? Let's go step-by-step:
Step1 (step=1): d0=[1,2,4,3] -> after op -> d1=[2,4,3,1].
Step2 (step=2): start d1, perform op -> d2=[4,3,1,2].
Now step=3: start d2, front=4 => s_start=3. So s_start=3 equals first max index? first max index is 3 (1-indexed). So matches.
Thus s_start equals first max index. But we don't need to rely on it.
Now we must also consider the possibility that after breaking, the tail length is n-1. But what if we break at step s_start, but the deque size might be less than n? No, operation never changes size.
Now we need to confirm that for n=2, after breaking, tail length is 1, as we capture.
Now code.
Potential improvements: We can avoid storing history for all steps if we only answer queries, but it's fine.
Now test with sample input.
Now think about potential issue with Python's deque indexing: d[0] is O(1). Good.
Now one more nuance: In the simulation loop, we check d[0]==M before performing operation. But what if after some steps, the front becomes M but there are still queries with m less than s_start? That's fine.
Now edge: if n=2 and s_start=2, we break at step=2. We have recorded history[1]. Good.
Now let's run through an example where s_start is computed correctly with duplicates: a=[2,2,1] we did.
Now we must also handle the case where after breaking, tail may contain the maximum value and we compute B as that max. That's fine.
Now about memory: history list of size n+1 may be large but okay.
Now about Python recursion? Not used.
Now about multiple test cases? Input only one test case.
Now final code with necessary imports.
Now answer.
But wait, there's another nuance: The process described is exactly the same as "deque game" but note that the operation writes to the beginning and end after taking the two. Our simulation models that. However, there might be alternative interpretation: after taking A and B, if A > B, then he writes A to the beginning (so A becomes new first) and writes B to the end (so B becomes last). That's exactly what we do. For else, writes B to beginning, A to end. Good.
Now final code.
But before finalizing, consider this: The teacher asks for "which two elements he will pull out on the m_j-th operation". That is exactly the pair (A,B) before the operation. So for m large, we need to output them.
Now I will produce final answer.
Now we might consider using a list to simulate instead of deque for faster indexing? But deque is fine.
Now we need to be careful about reading the input: The line after n q may have many numbers? The second line contains n integers. Then q lines each contain one integer. But q could be 0, then there are no lines after. So our reading with split and iter works.
Now check sample input:
5 3
1 2 3 4 5
1
2
10
Our reading: data = ["5","3","1","2","3","4","5","1","2","10"]; n=5,q=3; a = [1,2,3,4,5]; queries = [1,2,10]. Works.
Now for q=0: data = ["2","0","0","0"]; n=2,q=0; a=[0,0]; queries empty. The loop for queries will be zero iterations. Good.
Now code final.
Now double-check on index calculation: period = n-1. For n=2, period=1, modulo works.
Now check for n=2, a=[1,0] -> M=1, s_start=1, tail=[0]; m=1 -> (1,0); m=2 -> (1,0). Good.
Now think about time for reading/writing.
Now I'll produce final answer.
But there is a known Codeforces problem "A. Game of Deque" maybe similar. The intended solution is exactly this.
Now let's consider if there is any trick: maybe the process after the max is at front, the tail rotation might not be exactly the list we captured because there might have been an operation at the moment the max becomes front that hasn't been performed? But we capture tail at the beginning of step s_start, which is before that operation. So for step s_start, B = tail[0]. After performing step s_start, the tail rotates, and then step s_start+1 uses the rotated tail's first element, which is tail[1] (if length >1). That matches our indexing: (m - s_start) mod (n-1) gives tail[0] for m=s_start, tail[1] for m=s_start+1, etc. So correct.
Now confirm with example where s_start=5, tail=[1,2,3,4]; for m=5 => idx=0 -> (5,1); m=6 -> idx=1 -> (5,2); m=9 -> idx=(9-5)=4 mod4=0? (9-5=4, 4%4=0) -> (5,1) but earlier they said step9 gave (5,1)? Actually in example, step9 gave (5,1) (since at step9 state [5,1,2,3,4]? Let's check: In example, step9 had A=5,B=1? Actually they wrote: "9. [5, 1, 2, 3, 4]" That is state after step8? Wait, they label "9. [5,1,2,3,4]" and "10. [5,2,3,4,1] ⇒ A = 5, B = 2." So step9's A and B? According to labeling, "9. [5,1,2,3,4]" is a state, presumably after step8. Then step9 is performed on that state, resulting in state10. At step9, A=5,B=1. So m=9 => (5,1). According to our formula: s_start=5, tail=[1,2,3,4]; m=9 => idx=(9-5)=4 mod4=0 -> tail[0]=1 -> (5,1). Yes.
But we must consider that the number of steps to bring max to front might be less than the first max index? Let's test with a counterexample: Suppose we have [3,1,2]? max=3 at index1, s_start=1. That's index.
Now suppose [2,1,3]? max at index3, s_start=3, as earlier.
Now what about [2,3,1]? max at index2, s_start=2. So matches.
Now what about [4,2,3,5]? max at index4, s_start? Simulate: step1: 4>2 => d=[4,3,5,2]; step2: d[0]=4 !=5? Actually 4<5? step2: A=4,B=3? Wait after step1: d=[4,3,5,2]. Step2: A=4,B=3 => 4>3 => d=[4,5,2,3]; step3: d[0]=4 !=5? Actually A=4,B=5 => 4<5 => d=[5,2,3,4]; step4: front=5 => s_start=4. So s_start=4 equals index of max (4). Good.
Now consider [5,4,3,2,1] -> s_start=1.
All good.
Now we can commit.
One more nuance: The problem states n up to 1e5, q up to 3e5, and m up to 1e18. Our modulo uses n-1 which is up to 99999. So fine.
Now final code.
But I recall that in Python, using a deque and performing many popleft/append operations might be slower than using list with pointers? But 1e5 is fine.
Now we can also implement simulation using a list and two pointers (circular buffer) for speed, but not necessary.
Now I'll produce final answer.
But before final, let's think: Is there any scenario where after max becomes front, the tail rotation might not be simple because of equal comparisons? We already argued it is still a left rotation. Let's verify with a case where tail includes values equal to M. In step when second element equals M (front also M), we have A=M, B=M. Operation: else branch: push front B (M), push back A (M). After removal, we have rest (tail after first element). Then new deque: front M, then rest, then back M. So new tail = rest + [M]. Since original tail T = [M, rest], new tail = rest + [M] which is T rotated left. So indeed rotation. So it's consistent.
Thus final answer.
Now I'll write the solution explanation.
But note: In the code, when we break, we compute tail = list(d)[1:]. However, after many operations, d is a deque; converting to list is O(n). That's fine but we need to ensure we only do it once. It's okay.
But there is a subtlety: In the loop, we break when d[0]==M. At that point, we haven't performed the operation for that step. But what if s_start = n and after breaking, we capture tail. That's fine.
Now we should also handle the case where s_start could be 0? No step starts at 1.
Now about step increment: We increment step after performing operation. So step always points to the next step number. At start, step=1. After performing step1, step becomes 2. So at the beginning of iteration, step is the current step number to be processed. So breaking when d[0]==M sets s_start = step, which is the step number we would process next. So it's the first step where front is M.
Now confirm with s_start=1: step=1, d[0]==M true, break => s_start=1.
Now with s_start=5: after performing step4, step becomes 5. At top of loop, step=5, check d[0]==M true, break => s_start=5.
Thus works.
Now edge: In the scenario where we break immediately, we haven't recorded any history. So for queries with m < s_start, there are none because s_start=1, so m>=1 always >= s_start. So history not needed.
Now for s_start>1, we have history for steps 1..s_start-1.
Now ensure that we allocated history list of size n+1, and we store at indices up to s_start-1. So for query m < s_start, we can index directly. Good.
Now also note: If q is large and we print many lines, use sys.stdout.write with join is efficient.
Now we'll produce final solution.
Now think about alternative: Could there be a situation where the maximum is not unique and the front becomes M but not all occurrences of M are in the tail? That's fine.
Now final.
But I want to test a case where n=2 and a=[0,0]. M=0, s_start=1, tail=[0]. Queries: m=1 => (0,0) correct. After step1: (0,0) -> op: equal => push front0, push back0 => same. So (0,0) for all steps. Formula: m>=1 => (0,0). Good.
Now test case n=3, a=[1,1,1] all equal. M=1, first max index1 => s_start=1, tail=[1,1]. So for m=1: (1,1). m=2: idx=(2-1)%2=1 => tail[1]=1 => (1,1). m=3: idx=(3-1)%2=0 => tail[0]=1 => (1,1). So all (1,1). Let's simulate: step1: A=1,B=1 => equal => push front1, push back1 => d=[1,1,1]; step2: same. So correct.
Now test case n=4, a=[2,2,1,2] max=2, first max index1 => s_start=1, tail=[2,1,2]. For m=1: (2,2). For m=2: idx=1 => tail[1]=1 => (2,1). Simulate: step1: A=2,B=2 => equal => d=[2,1,2,2]? After removal we have [1,2]; push front2, push back2 => [2,1,2,2]; step2: A=2,B=1 => (2,1). So correct.
Now everything seems consistent.
Now I'll produce final answer.
But I recall a potential pitfall: In Python, using list(d)[1:] creates a new list, but if d is huge, it's okay. Alternatively, we can store tail by deque slicing: from collections import deque; but no slicing. So list conversion is fine.
Now we also need to consider that we might break before we have read all queries? No.
Now I'll write final solution with explanation.
Given the solution is straightforward, I'll provide final code.
Now note: In the problem, n can be up to 10^5 and q up to 3*10^5, and m up to 10^18. So we must use 64-bit integers, but Python int is arbitrary.
Now finalize.
But let's think about if there is a possibility that the process becomes periodic even before max becomes front, for example if the array is all equal? In that case, max is already front (since all equal, first element is max). So s_start=1. So no.
If there are only two distinct values and the max is at position 2, after step1, max becomes front, so s_start=2. So periodic starts at step2. So fine.
Thus final.
Now I'll produce answer.
Wait, I want to double-check the period length: After max at front, each operation rotates tail by one left, so after n-1 operations, the tail returns to original order? Since it's a rotation, after n-1 rotations, it returns to original. So period = n-1. Good.
Now confirm with n=2: period = 1, so constant.
Now answer.
Now code may be accepted.
Now I'll output final explanation and code.
But before final, check memory: tail list of size up to 99999, history list of size 100001 each storing two ints (Python objects). That's about 100k * (maybe 28 bytes each) ~ few MB, fine.
Now add safety: In simulation, if step becomes > n (maybe due to bug), we break and set s_start = step, tail = list(d)[1:]. But I think not needed.
Now let's implement.
Now I'll write the final solution. ```python
import sys
from collections import deque
def main():
data = sys.stdin.buffer.read().split()
it = iter(data)
n = int(next(it))
q = int(next(it))
a = [int(next(it)) for _ in range(n)]
queries = [int(next(it)) for _ in range(q)]
code
max_val = max(a)
dq = deque(a)
step = 1 # next operation number to execute
history = [None] * (n + 1) # pairs for steps < s_start
# Simulate until the first element becomes the global maximum
while True:
if dq[0] == max_val: # this step will have A = max_val
s_start = step
# save the current tail (elements 1 .. n-1)
tail = list(dq)[1:] # O(n), done once
break
# Perform one normal operation
A = dq.popleft()
B = dq.popleft()
history[step] = (A, B)
if A > B:
dq.appendleft(A)
dq.append(B)
else:
dq.appendleft(B)
dq.append(A)
step += 1
period = n - 1
out = []
for m in queries:
if m < s_start:
ans = history[m]
else:
idx = (m - s_start) % period
ans = (max_val, tail[idx])
out.append(f"{ans[0]} {ans[1]}")
sys.stdout.write("\n".join(out))