結果

問題 No.1630 Sorting Integers (Greater than K)
ユーザー 👑 rin204
提出日時 2021-07-30 20:49:45
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 178 ms / 2,000 ms
コード長 1,480 bytes
コンパイル時間 218 ms
コンパイル使用メモリ 82,304 KB
実行使用メモリ 117,928 KB
最終ジャッジ日時 2024-09-15 22:41:05
合計ジャッジ時間 3,360 ms
ジャッジサーバーID
(参考情報)
judge5 / judge1
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 5
other AC * 22
権限があれば一括ダウンロードができます

ソースコード

diff #

n, K = input().split()
n = int(n)
if len(K) > n:
    print(-1)
    exit()
K = K.zfill(n)
cnt = [0] + list(map(int, input().split()))
ans = []
ok = False
for k in K:
    k = int(k)
    if cnt[k] > 0:
        ans.append(str(k))
        cnt[k] -= 1
        continue
    flg = False
    for i in range(k + 1, 10):
        if cnt[i] > 0:
            flg = True
            ans.append(str(i))
            cnt[i] -= 1
            ok = True
            break
    if flg:
        for i, c in enumerate(cnt):
            ans += [str(i)] * c
        ok = True
        break
    while ans:
        p = int(ans.pop())
        cnt[p] += 1
        flg = False
        for i in range(p + 1, 10):
            if cnt[i] > 0:
                flg = True
                ans.append(str(i))
                cnt[i] -= 1
                break
        if flg:
            break
    if ans:
        for i, c in enumerate(cnt):
            ans += [str(i)] * c
        ok = True
        break
    else:
        print(-1)
        exit()
if ok:
    print("".join(ans))
else:
    while ans:
        p = int(ans.pop())
        cnt[p] += 1
        flg = False
        for i in range(p + 1, 10):
            if cnt[i] > 0:
                flg = True
                ans.append(str(i))
                cnt[i] -= 1
                break
        if flg:
            break
    if ans:
        for i, c in enumerate(cnt):
            ans += [str(i)] * c
        print("".join(ans))
    else:
        print(-1)
        
0