公式

C - カードの連結 / Card Concatenation 解説 by admin 印刷ページ

Claude Opus 5 (High)

Overview

In this problem, given \(N\) cards with a single-digit number written on each, we want to choose exactly \(K\) cards with numbers greater than or equal to \(X\) and arrange them in any order to form the largest possible integer. If there are fewer than \(K\) such cards, output \(-1\).

Analysis

Observation 1: Each card is a single digit

From the constraint \(1 \leq A_i \leq 9\), every card contains a single-digit number. Therefore, any integer formed by arranging \(K\) cards will always have exactly \(K\) digits. Because the number of digits is always fixed, there is no trade-off such as “using smaller numbers to increase the number of digits.”

Observation 2: Greedily pick the largest numbers

When comparing two \(K\)-digit integers, the integer with larger digits in more significant place values is greater. Therefore:

  • Cards to choose: Among the cards with numbers \(\geq X\), choose the \(K\) cards with the largest numbers.
  • Arrangement: Arrange the chosen \(K\) cards in descending order.

This strategy is optimal.

Let us briefly verify why this is optimal. If the chosen \(K\) cards contain a card \(a\) while an available, strictly larger card \(b\) (\(b > a\)) was left unchosen, replacing \(a\) with \(b\) and rearranging in descending order will strictly increase the value at the most significant differing digit, always yielding an improvement. Thus, selecting the top \(K\) largest available cards is optimal, and arranging them in descending order maximizes the value.

Issues with Naive Approaches

  • Trying all permutations: Since \(K \leq 18\), checking \(18!\) permutations will not run in time at all.
  • Sorting all cards \(\geq X\): Since \(N \leq 10^6\), an \(O(N \log N)\) approach might pass, but in Python it tends to be quite slow, especially due to input processing overhead.

Solution: Counting Sort (Buckets)

There are at most \(9\) distinct digit values, from \(1\) to \(9\). Thus, if we maintain an array cnt[1..9] counting the occurrences of each digit, sorting is unnecessary. We simply iterate through \(d = 9, 8, \dots, X\) in descending order and use up to cnt[d] cards (or the remaining needed count, whichever is smaller) until we reach the required number of cards.

Algorithm

  1. Count the occurrences of each digit \(d\) in cnt[d] (\(d = 1, \dots, 9\)).
  2. If \(\sum_{d=X}^{9} \mathrm{cnt}[d] < K\), output \(-1\) and terminate.
  3. Set need = K, and iterate \(d\) from \(9\) down to \(X\):
    • Take take = min(cnt[d], need) copies of digit \(d\).
    • Append take copies of \(d\) to the result string, and update need -= take.
    • Break out of the loop once need == 0.
  4. Output the result string.

Concrete example: Suppose \(N=6, K=4, X=3\), and \(A = (5,3,9,5,2,9)\). There are \(5\) cards \(\geq X=3\) (namely \(5,3,9,5,9\)), which is \(\geq K=4\), so the answer is not \(-1\). The counts are cnt[9]=2, cnt[5]=2, cnt[3]=1. Taking two \(9\)s and two \(5\)s in descending order makes need=0, giving the answer 9955.

Complexity

  • Time complexity: \(O(N + K)\) (the number of distinct digits, \(9\), is a constant)
  • Space complexity: \(O(N)\) (to store the input; the count array itself is \(O(1)\), and the output string is \(O(K)\))

Implementation Notes

  • Fast I/O: Since \(N \leq 10^6\), avoid calling input() \(N\) times. Instead, read all input at once using sys.stdin.buffer.read().split().

  • Omit integer conversion: Since each \(A_i\) is a single digit, we can convert it to an integer using data[i][0] - 48 (subtracting ASCII '0' \(= 48\) from the first byte of the byte string) instead of int(data[i]). This avoids \(10^6\) calls to int(), significantly improving the constant factor.

  • The answer is a large integer: Since \(K \leq 18\), it fits within a \(64\)-bit integer, but there is actually no need to convert it into an integer at all. Directly creating and concatenating strings like chr(48+d) * take and printing the result is both safe and fast.

  • Print at once: Output everything at once at the end using ''.join(res).

  • Check for \(-1\) first: While you could detect the shortage of cards after or during the greedy selection, checking the total number of cards \(\geq X\) beforehand makes the branching cleaner and simpler.

    Source Code

import sys

def main():
    data = sys.stdin.buffer.read().split()
    n = int(data[0]); k = int(data[1]); x = int(data[2])
    cnt = [0] * 10
    for i in range(3, 3 + n):
        cnt[data[i][0] - 48] += 1
    res = []
    need = k
    total = 0
    for d in range(9, x - 1, -1):
        total += cnt[d]
    if total < k:
        print(-1)
        return
    for d in range(9, x - 1, -1):
        take = cnt[d]
        if take > need:
            take = need
        if take:
            res.append(chr(48 + d) * take)
            need -= take
        if need == 0:
            break
    sys.stdout.write(''.join(res) + '\n')

main()

This editorial was generated by claude5opus-high.

投稿日時:
最終更新: