Waterloo 2023 Winter A - So I'll Max Out My Constructive Algorithm Skills
View as PDF2023 Winter Waterloo Local Contest, Problem A
BaoBao the Witch is stuck in a maze with  rows and 
 columns, where the height of the cell in the 
row and the 
 column is 
. To get out of the maze, BaoBao has to find a path which passes through
each cell exactly once. Each time she can only move into the neighboring cell sharing a same edge with
the current one. But as we know, BaoBao is super lazy, so every time when she climbs up (that is to
say, moving from a cell with a smaller height to another with a larger height) her happiness value will
decrease. As her helping hand, your task is to find a valid path so that when moving along the path, the
number of times BaoBao climbs up will not be more than the number of times she climbs down.
More formally, you need to find a sequence 
 such that:
- For all 
,
;
 - For all 
,
,
 - For all 
,
;
 where
equals
when
is true, and equals
when it is false.
Additionally, you discover that the heights in all cells are a permutation of , so you just need to output
the height of each cell in a valid path.
Input Specification
There are multiple test cases. The first line of the input contains an integer  
 indicating
the number of test cases. For each test case:
The first line contains an integer  
 indicating the size of the maze.
For the following  lines, the 
 line contains 
 integers 
 
 where 
 indicates the height of the cell in the 
 row and the 
 column. It's guaranteed that all integers in
the input make up a permutation of 
.
Output Specification
For each test case output one line containing  separated by a space indicating the heights of each cell
in a valid path. If there are multiple valid answers you can output any of them. It's easy to prove that an
answer always exists.
Please, DO NOT output extra spaces at the end of each line, or your answer may be considered incorrect!
Sample Input
1
2
4 3
2 1
Sample Output
4 3 1 2
Comments