This is the hard version of the problem. The only difference between the easy and hard versions is that the hard version asks you to construct an example of a satisfactory tree.
As an Earth mage, Rae has mastered the spell of growing trees! But Manaria brags that she can grow a more impressive species of trees. Rae remembers that the most rare type of tree can be grown using a formula represented by a certain permutation — please help her construct it!
You are given a permutation$$$^{\text{∗}}$$$ $$$p$$$ of length $$$n$$$.
Determine if there exists an undirected tree with $$$n$$$ vertices labeled $$$1, 2, \dots, n$$$, satisfying the following condition:
Additionally, if there exists such a tree, output any of them.
$$$^{\text{∗}}$$$A permutation of length $$$n$$$ is an array that contains every integer from $$$1$$$ to $$$n$$$ exactly once, in any order.
The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases.
The first line of each test case contains a single integer $$$n$$$ ($$$2\leq n\leq 2\cdot 10^5$$$).
The second line of each test case contains $$$n$$$ integers, $$$p_1, p_2, \dots, p_n$$$ ($$$1\leq p_i\leq n$$$). It is guaranteed that all $$$p_i$$$ are distinct.
It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$2\cdot 10^5$$$.
For each test case, output on a single line "Yes" if there exists a tree satisfying the given condition, and "No" otherwise.
Then, if the answer is "Yes", output $$$n-1$$$ lines. The $$$i$$$-th of these lines should contain two integers $$$u$$$ and $$$v$$$, denoting an edge connecting vertices $$$u$$$ and $$$v$$$.
You may output the answer in any case (upper or lower). For example, the strings "yEs", "yes", "YES", and "yeS" will be recognized as "Yes".
961 3 4 5 2 643 4 1 254 3 5 1 241 2 3 474 3 5 7 6 2 162 4 6 1 3 532 1 342 4 1 364 2 6 5 1 3
Yes 3 1 4 1 6 5 6 2 6 1 No No Yes 2 1 4 3 4 1 No Yes 4 2 6 2 3 1 5 1 5 2 Yes 3 2 3 1 Yes 4 2 3 1 3 2 Yes 6 4 6 2 3 1 5 4 2 3
In the first example, we can construct the tree given in the sample output. We have that
In the second example, it can be shown that there does not exist a tree satisfying the given constraints.