CF2171F Rae Taylor and Trees (hard version)

Description

"To think a commoner would even fathom sitting next to me. Know your place!" — Claire François 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: - Let $ u $ and $ v $ ( $ 1\leq {\color{red}{u < v}} \leq n $ ) be any two vertices connected by an edge. Then $ u $ appears before $ v $ in $ p $ . 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.

Input Format

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 $ .

Output Format

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".

Explanation/Hint

In the first example, we can construct the tree given in the sample output. We have that - $ 1 < 3 $ , and $ 1 $ appears before $ 3 $ in $ p $ , - $ 1 < 4 $ , and $ 1 $ appears before $ 4 $ in $ p $ , - $ 5 < 6 $ , and $ 5 $ appears before $ 6 $ in $ p $ , - $ 2 < 6 $ , and $ 2 $ appears before $ 6 $ in $ p $ , - $ 1 < 6 $ , and $ 1 $ appears before $ 6 $ in $ p $ . In the second example, it can be shown that there does not exist a tree satisfying the given constraints.