結果
問題 |
No.1630 Sorting Integers (Greater than K)
|
ユーザー |
![]() |
提出日時 | 2025-06-12 21:15:47 |
言語 | PyPy3 (7.3.15) |
結果 |
TLE
|
実行時間 | - |
コード長 | 2,940 bytes |
コンパイル時間 | 222 ms |
コンパイル使用メモリ | 82,116 KB |
実行使用メモリ | 262,828 KB |
最終ジャッジ日時 | 2025-06-12 21:16:58 |
合計ジャッジ時間 | 9,898 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge5 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
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()