結果

問題 No.927 Second Permutation
コンテスト
ユーザー lam6er
提出日時 2025-03-20 20:19:49
言語 PyPy3
(7.3.17)
コンパイル:
pypy3 -mpy_compile _filename_
実行:
pypy3 _filename_
結果
AC  
実行時間 99 ms / 2,000 ms
コード長 736 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 248 ms
コンパイル使用メモリ 96,096 KB
実行使用メモリ 89,472 KB
最終ジャッジ日時 2026-07-07 08:49:12
合計ジャッジ時間 4,482 ms
ジャッジサーバーID
(参考情報)
judge1_0 / judge2_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 27
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

import sys

def all_same(s):
    return all(c == s[0] for c in s)

def previous_permutation(arr):
    n = len(arr)
    i = n - 2
    while i >= 0 and arr[i] <= arr[i + 1]:
        i -= 1
    if i == -1:
        return False
    j = n - 1
    while arr[j] >= arr[i]:
        j -= 1
    arr[i], arr[j] = arr[j], arr[i]
    arr[i + 1:] = reversed(arr[i + 1:])
    return True

def solve():
    X = sys.stdin.readline().strip()
    digits = list(X)
    if all_same(digits):
        print(-1)
        return
    max_digits = sorted(digits, key=lambda x: -int(x))
    if not previous_permutation(max_digits):
        print(-1)
        return
    if max_digits[0] == '0':
        print(-1)
    else:
        print(''.join(max_digits))

solve()
0