結果

問題 No.39 桁の数字を入れ替え
ユーザー norioc
提出日時 2024-07-02 22:57:33
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 49 ms / 5,000 ms
コード長 699 bytes
コンパイル時間 182 ms
コンパイル使用メモリ 82,012 KB
実行使用メモリ 52,480 KB
最終ジャッジ日時 2024-07-02 22:57:37
合計ジャッジ時間 1,820 ms
ジャッジサーバーID
(参考情報)
judge1 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 19
権限があれば一括ダウンロードができます

ソースコード

diff #

N = int(input())

ls = [-1] * 10
rs = [-1] * 10
for i, d in enumerate(map(int, str(N))):
    if ls[d] == -1:
        ls[d] = i

    rs[d] = i


cands = []
for i in range(1, 10):  # 入れ替え要素(左)
    if ls[i] == -1: continue
    for j in reversed(range(i+1, 10)):  # 入れ替え要素(右)
        if rs[j] == -1: continue
        if ls[i] >= rs[j]: continue  # 入れ替えると小さくなる

        # 左: 位置がより左を優先
        # 右: 値がより大きいのを優先
        cands.append([(ls[i], i), (-j, rs[j])])

if not cands:
    print(N)
    exit()

a, b = min(cands)
s = list(str(N))

ai, bi = a[0], b[1]
s[ai], s[bi] = s[bi], s[ai]
ans = ''.join(s)
print(ans)
0