Erdős and Szekeres Sequence Reconstruction
Time limit5sMemory limit512 MB
Rebuild the lexicographically smallest permutation of 1 to N whose increasing and decreasing subsequence lengths match the given arrays.
- Level
Medium7 of 10
- Topics
- Backtracking, Greedy, Dynamic programming
- Solved
- No attempts yet
Problem
is a sequence that lists the numbers through , each exactly once. Take some entries of in their original order. If the values keep growing, the entries form an increasing subsequence; if they keep shrinking, they form a decreasing subsequence. For example, is an increasing subsequence of .
Paul Erdős and George Szekeres proved that always contains an increasing subsequence of length at least or a decreasing subsequence of length at least . The sequence above contains the decreasing subsequence of length 4.
Two values are defined for each .
- is the maximum length of an increasing subsequence whose largest number is .
- is the maximum length of a decreasing subsequence whose largest number is .
The largest number of an increasing subsequence is its last entry, so equals the maximum length of an increasing subsequence that ends at . The largest number of a decreasing subsequence is its first entry, so equals the maximum length of a decreasing subsequence that starts at .
For the values are:
The pair differs for every , and that forces or to be at least for some .
Given and , reconstruct . The answer must list the numbers through exactly once each. If several sequences are possible, print the lexicographically smallest one: make as small as possible, then make as small as possible among what is left, and so on.
Input
The first line holds the number of test cases . Each test case takes three lines.
The first line holds one integer . The second line holds separated by spaces. The third line holds separated by spaces.
Limits
- and are positive integers.
- At least one valid exists.
Output
For each test case print one line with Case #x: followed by separated by spaces. Here is the test case number, counting from 1.