Codeforces Round 794 (Div. 1)
D2
Permutation Weight (Hard Version)
Codeforces
3500
原题
← D1E →
翻译中…

This is a hard version of the problem. The difference between the easy and hard versions is that in this version, you have to output the lexicographically smallest permutation with the smallest weight.

翻译中…

You are given a permutation $p_1, p_2, \ldots, p_n$ of integers from $1$ to $n$.

翻译中…

Let's define the weight of the permutation $q_1, q_2, \ldots, q_n$ of integers from $1$ to $n$ as $$|q_1 - p_{q_{2}}| + |q_2 - p_{q_{3}}| + \ldots + |q_{n-1} - p_{q_{n}}| + |q_n - p_{q_{1}}|$$

翻译中…

You want your permutation to be as lightweight as possible. Among the permutations $q$ with the smallest possible weight, find the lexicographically smallest.

翻译中…

Permutation $a_1, a_2, \ldots, a_n$ is lexicographically smaller than permutation $b_1, b_2, \ldots, b_n$, if there exists some $1 \le i \le n$ such that $a_j = b_j$ for all $1 \le j \lt i$ and $a_i \lt b_i$.

翻译中…

Input

翻译中…

The first line of the input contains a single integer $t$ ($1 \le t \le 100$)  — the number of test cases. The description of the test cases follows.

翻译中…

The first line of each test case contains a single integer $n$ ($2 \le n \le 200$)  — the size of the permutation.

翻译中…

The second line of each test case contains $n$ integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$, all $p_i$ are distinct)  — the elements of the permutation.

翻译中…

The sum of $n$ over all test cases doesn't exceed $400$.

翻译中…

Output

翻译中…

For each test case, output $n$ integers $q_1, q_2, \ldots, q_n$ ($1 \le q_i \le n$, all $q_i$ are distinct)  — the lexicographically smallest permutation with the smallest weight.

翻译中…

Note

翻译中…

In the first test case, there are two permutations of length $2$: $(1, 2)$ and $(2, 1)$. Permutation $(1, 2)$ has weight $|1 - p_2| + |2 - p_1| = 0$, and the permutation $(2, 1)$ has the same weight: $|2 - p_1| + |1 - p_2| = 0$. In this version, you have to output the lexicographically smaller of them  — $(1, 2)$.

翻译中…

In the second test case, the weight of the permutation $(1, 3, 4, 2)$ is $|1 - p_3| + |3 - p_4| + |4 - p_2| + |2 - p_1| = |1 - 1| + |3 - 4| + |4 - 3| + |2 - 2| = 2$. There are no permutations with smaller weights.

翻译中…

In the third test case, the weight of the permutation $(1, 3, 4, 2, 5)$ is $|1 - p_3| + |3 - p_4| + |4 - p_2| + |2 - p_5| + |5 - p_1| = |1 - 3| + |3 - 2| + |4 - 4| + |2 - 1| + |5 - 5| = 4$. There are no permutations with smaller weights.

翻译中…

样例

Input #1
3
2
2 1
4
2 3 1 4
5
5 4 3 2 1
Output #1
1 2
1 3 4 2
1 3 4 2 5
InputCopy OutputCopy
题目信息
题号
1685D2
时间限制
1 s
内存限制
256 MB
标签
构造
贪心

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。