結果

問題 No.1051 PQ Permutation
ユーザー betrue12
提出日時 2020-05-09 02:26:40
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 248 ms / 2,000 ms
コード長 1,366 bytes
コンパイル時間 2,966 ms
コンパイル使用メモリ 207,556 KB
最終ジャッジ日時 2025-01-10 09:33:10
ジャッジサーバーID
(参考情報)
judge3 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

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

void answer(vector<int> A){
    int N = A.size();
    for(int i=0; i<N; i++) cout << A[i]+1 << " \n"[i==N-1];
    exit(0);
}

int main(){
    int N, P, Q;
    cin >> N >> P >> Q;
    P--; Q--;
    vector<int> A(N);
    for(int i=0; i<N; i++) cin >> A[i], A[i]--;

    if(!next_permutation(A.begin(), A.end())) fail();
    int posP = -1, posQ = -1;
    for(int i=0; i<N; i++){
        if(A[i] == P) posP = i;
        if(A[i] == Q) posQ = i;
    }
    if(posP < posQ) answer(A);

    sort(A.begin()+posQ+1, A.end(), greater<>());

    set<int> avail;
    for(int i=posQ+1; i<N; i++) avail.insert(A[i]);
    while(true){
        int pt = posQ;
        while(pt >= 0 && A[pt] > A[pt+1]){
            avail.insert(A[pt]);
            pt--;
        }
        if(pt == -1) fail();
        if(*avail.lower_bound(A[pt]) == Q){
            swap(A[pt], A[posQ]);
            avail.erase(Q);
            avail.insert(A[posQ]);
            posQ = pt;
        }else{
            break;
        }
    }

    if(!next_permutation(A.begin(), A.end())) fail();
    for(int i=0; i<N; i++){
        if(A[i] == P) posP = i;
        if(A[i] == Q) posQ = i;
    }
    if(posP < posQ) answer(A);

    A.erase(A.begin()+posQ);
    A.insert(A.begin()+posP, Q);
    answer(A);
    return 0;
}
0