結果

問題 No.1051 PQ Permutation
ユーザー 👑 rin204
提出日時 2023-12-29 16:04:00
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 163 ms / 2,000 ms
コード長 2,274 bytes
コンパイル時間 481 ms
コンパイル使用メモリ 82,336 KB
実行使用メモリ 112,036 KB
最終ジャッジ日時 2024-09-27 16:14:17
合計ジャッジ時間 6,290 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 46
権限があれば一括ダウンロードができます

ソースコード

diff #

def next_permutation(P):
    n = len(P)
    for i in range(n - 2, -1, -1):
        if P[i] < P[i + 1]:
            l = i + 1
            r = n - 1
            while r > l:
                P[l], P[r] = P[r], P[l]
                l += 1
                r -= 1
            for j in range(i + 1, n):
                if P[i] < P[j]:
                    P[i], P[j] = P[j], P[i]
                    return True
    return False


def all_permutations(P):
    # 全列挙したい場合はソートしてある状態で渡す
    yield P
    while next_permutation(P):
        yield P


def prev_permutation(P):
    n = len(P)
    for i in range(n - 2, -1, -1):
        if P[i] > P[i + 1]:
            l = i + 1
            r = n - 1
            while r > l:
                P[l], P[r] = P[r], P[l]
                l += 1
                r -= 1
            for j in range(i + 1, n):
                if P[i] > P[j]:
                    P[i], P[j] = P[j], P[i]
                    return True
    return False


def rev_all_permutations(P):
    # 全列挙したい場合は逆順ソートしてある状態で渡す
    yield P
    while prev_permutation(P):
        yield P


n, p, q = map(int, input().split())
A = list(map(int, input().split()))
if not next_permutation(A):
    print(-1)
    exit()


pp = -1
qq = -1
for i, a in enumerate(A):
    if a == p:
        pp = i
    if a == q:
        qq = i

if pp < qq:
    print(*A)
    exit()

if q < p:
    B = A[qq:]
    A = A[:qq]
    mi = 1 << 30
    for b in B:
        if b > q and b < mi:
            mi = b

    A.append(mi)
    B.remove(mi)
    B.sort()
    if mi == p:
        A += B
    else:
        for b in B:
            if b == q:
                pass
            elif b == p:
                A += [p, q]
            else:
                A.append(b)

    print(*A)
else:
    ma = -1
    ind = -1
    for i in range(n - 1, -1, -1):
        if A[i] > ma and A[i] != q:
            ma = A[i]
        if i <= qq and ma > A[i]:
            ind = i
            break

    if ind == -1:
        print(-1)
        exit()

    B = A[ind:]
    A = A[:ind]

    mi = 1 << 30
    for b in B:
        if b > B[0] and b != q and b < mi:
            mi = b

    A.append(mi)
    B.remove(mi)
    B.sort()
    A += B
    print(*A)
0