結果
| 問題 |
No.1630 Sorting Integers (Greater than K)
|
| コンテスト | |
| ユーザー |
gew1fw
|
| 提出日時 | 2025-06-12 16:37:43 |
| 言語 | PyPy3 (7.3.15) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 2,940 bytes |
| コンパイル時間 | 175 ms |
| コンパイル使用メモリ | 82,084 KB |
| 実行使用メモリ | 263,356 KB |
| 最終ジャッジ日時 | 2025-06-12 16:37:53 |
| 合計ジャッジ時間 | 9,630 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 5 |
| other | AC * 12 TLE * 2 -- * 8 |
ソースコード
import sys
from copy import deepcopy
def can_form_larger(counts, s):
if not s:
return False
current_counts = counts.copy()
for i in range(len(s)):
current_digit = int(s[i])
# Check if any digit larger than current_digit exists
for d in range(current_digit + 1, 10):
if current_counts[d] > 0:
return True
# Check if current_digit is available
if current_counts[current_digit] == 0:
return False
current_counts[current_digit] -= 1
return False
def solve():
N, K = sys.stdin.readline().split()
N = int(N)
c = list(map(int, sys.stdin.readline().split()))
counts = [0] * 10 # counts[1..9] are used
for i in range(9):
counts[i+1] = c[i]
if len(K) != N:
if len(K) > N:
print(-1)
return
else:
# Form the smallest possible N-digit number
res = []
for d in range(1, 10):
res.append(str(d) * counts[d])
res = ''.join(res)
if len(res) == N:
print(res)
else:
print(-1)
return
# Now, len(K) == N
current_counts = deepcopy(counts)
prefix = []
for i in range(N):
current_digit = int(K[i])
found = False
for d in range(current_digit, 10):
if current_counts[d] == 0:
continue
if d > current_digit:
# Use this d and fill the rest with sorted remaining digits
temp_counts = current_counts.copy()
temp_counts[d] -= 1
remaining = []
for digit in range(1, 10):
remaining.append(str(digit) * temp_counts[digit])
remaining = ''.join(remaining)
candidate = ''.join(prefix) + str(d) + remaining
if len(candidate) != N:
continue
if candidate > K:
print(candidate)
return
else:
# Check if using d allows remaining digits to form a larger number
temp_counts = current_counts.copy()
temp_counts[d] -= 1
if can_form_larger(temp_counts, K[i+1:]):
current_counts[d] -= 1
prefix.append(str(d))
found = True
break
if not found:
# Check if we can use current_digit
if current_counts[current_digit] > 0:
current_counts[current_digit] -= 1
prefix.append(str(current_digit))
else:
print(-1)
return
# After processing all digits, check if the formed number is larger than K
formed = ''.join(prefix)
if formed > K:
print(formed)
else:
print(-1)
solve()
gew1fw