A - 図鑑コンプリート / Encyclopedia Completion Editorial by admin Editorial for printing
Claude 4.5 OpusOverview
This is a problem where you select only the first flower found for each species from among the flowers you discovered, and calculate the count and sum of species numbers.
Analysis
The key point of this problem is “when the same species number appears multiple times, only adopt the first occurrence.”
For example, consider the case where flower species numbers are found in the order [3, 1, 2, 1, 3, 4]:
- 1st: Species 3 → First time seeing it → Adopt
- 2nd: Species 1 → First time seeing it → Adopt
- 3rd: Species 2 → First time seeing it → Adopt
- 4th: Species 1 → Already seen → Exclude
- 5th: Species 3 → Already seen → Exclude
- 6th: Species 4 → First time seeing it → Adopt
Result: The count is \(4\) flowers, and the sum of species numbers is \(3 + 1 + 2 + 4 = 10\).
Why use a set?
We need to efficiently determine “whether we’ve already seen it.”
- Naive approach (using a list): Scan through the entire list each time to check → Each check takes \(O(N)\), resulting in \(O(N^2)\) overall
- Using a set: Adding to and searching in a set is \(O(1)\) on average → \(O(N)\) overall
Since \(N\) can be up to \(2 \times 10^5\), \(O(N^2)\) might not be fast enough, but \(O(N)\) is sufficiently fast.
Algorithm
- Prepare a set
seento manage “species numbers already seen” - Initialize a variable
countfor counting flowers and a variabletotalfor holding the sum of species numbers to \(0\) - Process each flower one by one in the order they were found:
- If that species number is not contained in
seen:- Add that species number to
seen - Increment
countby \(1\) - Add that species number to
total
- Add that species number to
- If already contained in
seen, do nothing (exclude as duplicate)
- If that species number is not contained in
- Output the final
countandtotal
Complexity
- Time complexity: \(O(N)\)
- For each flower, adding to and searching in the set can be done in \(O(1)\) on average
- Processing \(N\) flowers sequentially results in \(O(N)\) overall
- Space complexity: \(O(\min(N, 100))\)
- The set
seencan contain at most 100 species (species numbers range from 1 to 100) - This can essentially be considered \(O(1)\) (constant)
- The set
Implementation Notes
Python’s
setcan perform element addition (add) and existence checking (in) in \(O(1)\) on average, making it ideal for “removing duplicates” operations like thisUse
if s not in seen:to check “is this a species we haven’t seen yet,” and only update the count and sum when the condition is metSince the range of species numbers is small (1 to 100), it’s also possible to implement this using an array (a list of size 101) and manage it like
seen[s] = TrueSource Code
N = int(input())
S = list(map(int, input().split()))
seen = set()
count = 0
total = 0
for s in S:
if s not in seen:
seen.add(s)
count += 1
total += s
print(count, total)
This editorial was generated by claude4.5opus.
posted:
last update: