Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code: Move Back at a Cost

#include <bits/stdc++.h>

using i64 = long long;
using u64 = unsigned long long;
using u32 = unsigned;
using u128 = unsigned __int128;

constexpr int inf = 1E9;

void solve() {
    int n;
    std::cin >> n;

    std::vector<int> a(n);
    for (int i = 0; i < n; i++) {
        std::cin >> a[i];
    }

    std::vector<int> stk, b;
    for (int i = 0; i < n; i++) {
        while (!stk.empty() && a[i] < stk.back()) {
            b.push_back(stk.back() + 1);
            stk.pop_back();
        }
        stk.push_back(a[i]);
    }

    std::sort(b.begin(), b.end());

    while (!b.empty() && stk.back() > b[0]) {
        b.push_back(stk.back() + 1);
        stk.pop_back();
    }

    std::sort(b.begin(), b.end());

    a = stk;
    for (auto x : b) {
        a.push_back(x);
    }

    for (int i = 0; i < n; i++) {
        std::cout << a[i] << " \n"[i == n - 1];
    }
}

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int t;
    std::cin >> t;

    while (t--) {
        solve();
    }

    return 0;
}