結果

問題 No.1051 PQ Permutation
ユーザー MisterMister
提出日時 2020-05-08 22:17:58
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 2,368 bytes
コンパイル時間 1,309 ms
コンパイル使用メモリ 84,756 KB
最終ジャッジ日時 2025-01-10 08:54:01
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 45 TLE * 1
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <algorithm>
#include <vector>
#include <cassert>

void fail() {
    std::cout << -1 << std::endl;
    std::exit(0);
}

void answer(const std::vector<int>& xs) {
    for (auto x : xs) std::cout << x << " ";
    std::cout << std::endl;
    std::exit(0);
}

void answer(const std::vector<int>& fs, const std::vector<int>& bs) {
    for (auto x : fs) std::cout << x << " ";
    for (auto x : bs) std::cout << x << " ";
    std::cout << std::endl;
    std::exit(0);
}

int pos(const std::vector<int>& xs, int x) {
    return std::find(xs.begin(), xs.end(), x) - xs.begin();
}

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

    std::vector<int> xs(n);
    for (auto& x : xs) std::cin >> x;

    if (!std::next_permutation(xs.begin(), xs.end())) fail();

    if (pos(xs, p) < pos(xs, q)) answer(xs);

    while (true) {
        int qi = pos(xs, q);
        std::vector<int>
            fs(xs.begin(), xs.begin() + qi),
            bs(xs.begin() + qi, xs.end());
        int m = bs.size();

        if (q > p) {
            int min = n + 1;
            for (int i = 0; i < m; ++i) {
                if (bs[i] > q) min = std::min(min, bs[i]);
            }

            if (min > n) {
                std::sort(bs.rbegin(), bs.rend());
                std::copy(bs.begin(), bs.end(), xs.begin() + qi);

                if (!std::next_permutation(xs.begin(), xs.end())) fail();
                if (pos(xs, p) < pos(xs, q)) answer(xs);
                continue;
            }

            auto ri = pos(bs, min);
            std::swap(bs.front(), bs[ri]);
            std::sort(bs.begin() + 1, bs.end());
            answer(fs, bs);

        } else {
            int min = n + 1;
            for (int i = 0; i < m; ++i) {
                if (bs[i] > q) min = std::min(min, bs[i]);
            }
            assert(min <= n);

            auto ri = pos(bs, min);
            std::swap(bs.front(), bs[ri]);
            std::sort(bs.begin() + 1, bs.end());

            if (pos(bs, p) < pos(bs, q)) answer(fs, bs);

            auto pi = pos(bs, p), qi = pos(bs, q);
            while (pi > qi) {
                std::swap(bs[qi], bs[qi + 1]);
                ++qi;
            }

            answer(fs, bs);
        }
    }
}

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

    solve();

    return 0;
}
0