C - 連続カード分け / Consecutive Card Distribution Editorial by admin
DeepSeek V3Overview
This problem asks you to find the minimum number of groups when dividing given cards into groups consisting of consecutive integers (consecutive-number groups).
Analysis
When dividing cards into consecutive-number groups, the key observation is that “consecutive integers can be included in the same group.” For example, if the cards are [1,2,3,5,6], they can be divided into 2 groups: [1,2,3] and [5,6].
A naive approach would be to try all possible partitions, but since the number of cards \(N\) can be as large as \(2 \times 10^5\), an exponential-time algorithm would not finish in time.
An efficient solution is to sort the cards and then use a greedy method to form groups. After sorting, we examine the cards from the beginning and add as many cards as possible to the current group (cards with values at most current value + 1). This allows us to extend each group as long as possible, thereby minimizing the total number of groups.
Algorithm
- Sort the integers written on the cards in ascending order.
- Examine the cards from the beginning and form groups using the following procedure:
- Set the current card as the starting point of a new group.
- While the next card has a value at most current value + 1, add it to the group.
- If a card with exactly current value + 1 is found, update the current value by +1.
- When no more cards can be added to the group, finalize the group and start a new group from the next card.
- Output the total number of groups created.
This greedy method can find the optimal group partition by scanning the sorted array just once.
Complexity
- Time complexity: \(O(N \log N)\) (dominated by the sorting step)
- Space complexity: \(O(N)\) (for the array storing the input data)
Implementation Notes
Efficiency is improved by reading all input data at once.
Although a nested loop is used for greedy grouping after sorting, each element is processed at most once across the outer and inner loops, so the overall complexity is \(O(N)\).
The end value of the current group is tracked to determine whether the next card should be included in the group.
By using the inner loop condition
A[j] <= current + 1, since there are no duplicate values, we can efficiently form groups while maintaining consecutiveness.Source Code
def main():
import sys
input = sys.stdin.read
data = input().split()
n = int(data[0])
A = list(map(int, data[1:1+n]))
A.sort()
count = 0
i = 0
while i < n:
count += 1
current = A[i]
j = i + 1
while j < n and A[j] <= current + 1:
if A[j] == current + 1:
current += 1
j += 1
i = j
print(count)
if __name__ == "__main__":
main()
This editorial was generated by deepseekv3.
posted:
last update: