So I’ll Max Out My Constructive Algorithm Skills

시간 제한1초메모리 제한1024 MB

요약
1부터 n^2까지의 순열이 담긴 n x n 격자에서, 오르는 횟수가 내려가는 횟수를 넘지 않는 해밀턴 경로를 따라 각 칸의 높이를 출력한다.
난이도

보통10점 중 6점

유형
구현, 그리디, 시뮬레이션
정답자
아직 제출이 없습니다

문제

BaoBao the Witch is stuck in a maze with nn rows and nn columns, where the height of the cell in the ii-th row and the jj-th column is h_i,jh\_{i,j}. 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 (x_1,y_1),(x_2,y_2),⋯ ,(x_n2,y_n2)(x\_1, y\_1),(x\_2, y\_2), \cdots ,(x\_{n^2}, y\_{n^2}) such that:

  • For all 1≤i≤n21 ≤ i ≤ n^2, 1≤x_i,y_i≤n1 ≤ x\_i , y\_i ≤ n;
  • For all 1≤i,j≤n21 ≤ i, j ≤ n^2, i≠ji \ne j, (x_i,y_i)≠(x_j,y_j)(x\_i , y\_i) \ne (x\_j , y\_j );
  • For all 2≤i≤n22 ≤ i ≤ n^2, ∣x_i−x_i−1∣+∣y_i−y_i−1∣=1|x\_i - x\_{i-1}| + |y\_i - y\_{i-1}| = 1;
  • ∑_i=2n2\[h_x_i−1,y_i−1<h_x_i,y_i]≤∑_i=2n2\[h_x_i−1,y_i−1>h_x_i,y_i]\displaystyle\sum\_{i=2}^{n^2}{\[h\_{x\_{i-1},y\_{i-1}} < h\_{x\_i, y\_i}]} \le \displaystyle\sum\_{i=2}^{n^2}{\[h\_{x\_{i-1},y\_{i-1}} > h\_{x\_i, y\_i}]}, where \[P]\[P] equals 11 when PP is true, and equals 00 when it is false.

Additionally, you discover that the heights in all cells are a permutation of n2n^2, so you just need to output the height of each cell in a valid path.

입력

There are multiple test cases. The first line of the input contains an integer TT (1≤T≤1001 ≤ T ≤ 100) indicating the number of test cases. For each test case:

The first line contains an integer nn (2≤n≤642 ≤ n ≤ 64) indicating the size of the maze.

For the following nn lines, the ii-th line contains nn integers h_i,1,h_i,2,⋯ ,h_i,nh\_{i,1}, h\_{i,2}, \cdots , h\_{i,n} (1≤h_i,j≤n21 ≤ h\_{i,j} ≤ n^2) where h_i,jh\_{i,j} indicates the height of the cell in the ii-th row and the jj-th column. It’s guaranteed that all integers in the input make up a permutation of n2n^2.

출력

For each test case output one line containing n2n^2 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.

예제1

  1. 예제 1

    입력
    1
    2
    4 3
    2 1
    
    예상 출력
    4 3 1 2