由于是字典序最大,所以我们可以:
先存一个原数组副本 。
再将 数组从大到小排序。
在这之后,发现只要 中和 第一个不同的位置换成 中的值就是最优的。
所以我们先从找到第一个 的位置,记为 ,然后从这个位置开始,找到最后一个最大值的位置,记为 最后翻转原数组的 至 就好了。
#include <bits/stdc++.h>
using ll = long long;
using ull = unsigned long long;
using i128 = __int128;
using db = double;
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define frep(i, b, a) for (int i = b; i >= a; i--)
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define pf push_front
#define mp make_pair
#define s second
#define f first
const int inf = 1e9;
const ll INF = 1LL << 60LL;
const int mod = 998244353;
const db eps = 1e-9;
std::mt19937_64 rng(std::chrono::system_clock::now().time_since_epoch().count());
const int N = 2e5 + 10;
int t, n, pos, a[N], b[N];
void solve() {
std::cin >> n;
pos = -1;
rep(i, 1, n) std::cin >> a[i], b[i] = a[i];
std::sort(b + 1, b + n + 1, std::greater<int>());
rep(i, 1, n) if (a[i] != b[i]) {
pos = i;
break;
}
if (pos == -1) {
rep(i, 1, n) std::cout << a[i] << " \n"[i == n];
return;
}
int pos1 = 0, mx = 0;
rep(i, pos, n) if (a[i] >= mx) mx = a[i], pos1 = i;
std::reverse(a + pos, a + pos1 + 1);
rep(i, 1, n) std::cout << a[i] << ' ';
std::cout << '\n';
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr), std::cout.tie(nullptr);
std::cin >> t;
while (t--) solve();
}