結果

問題 No.1051 PQ Permutation
ユーザー Mister
提出日時 2020-05-08 21:59:21
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 2,079 bytes
コンパイル時間 1,096 ms
コンパイル使用メモリ 81,384 KB
最終ジャッジ日時 2025-01-10 08:41:12
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 42 WA * 4
権限があれば一括ダウンロードができます

ソースコード

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);

    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) {
            if (!std::next_permutation(fs.begin(), fs.end())) fail();
            std::sort(bs.begin(), bs.end());
            answer(fs, bs);
        }

        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