A - クラス委員長の選出 / Election of the Class President Editorial by admin
Claude 4.6 Opus (Thinking)Overview
Given the vote counts of \(N\) students, output the student number if there is exactly one student with the most votes, or \(-1\) if there are multiple such students.
Analysis
The processing required for this problem consists of the following two steps:
- Find the maximum vote count: What is the largest value among all students’ vote counts?
- Count how many people have that maximum vote count: If it’s 1 person, the class president is determined; if it’s 2 or more, the president cannot be decided.
For example, consider the case where \(N = 5\) and the vote counts are [3, 5, 2, 5, 1].
- The maximum vote count is \(5\)
- There are 2 students who received \(5\) votes: student 2 and student 4
- Therefore, the class president cannot be determined, and the answer is \(-1\)
As another example, consider the case where the vote counts are [3, 7, 2, 5, 1]:
- The maximum vote count is \(7\)
- There is only 1 student who received \(7\) votes: student 2
- Therefore, the answer is \(2\)
This problem can be solved fast enough by simply scanning the list naively. Since \(N\) is at most \(2 \times 10^5\), an \(O(N)\) solution that scans the list a few times is perfectly fine.
Algorithm
- Find the maximum value
max_valfrom the vote count list \(A\) (max(A)). - Count how many elements in the list are equal to
max_val(A.count(max_val)). - If the count is \(1\), find the index of the element with the maximum value (
A.index(max_val)), convert it to 1-indexed, and output it. - If the count is \(2\) or more, output \(-1\).
Complexity
- Time complexity: \(O(N)\)
- One scan of the list with
max(A): \(O(N)\) - One scan of the list with
A.count(max_val): \(O(N)\) - At most one scan of the list with
A.index(max_val): \(O(N)\) - Total: \(O(N)\)
- One scan of the list with
- Space complexity: \(O(N)\) (for storing the list of vote counts)
Implementation Notes
Converting between 1-indexed and 0-indexed: Python lists start from 0 (0-indexed), but in the problem, student numbers start from 1 (1-indexed). Since
A.index(max_val)returns a 0-indexed position, you need to add+1when outputting.Using
countandindex: Python lists have convenient methods —counteasily retrieves the number of occurrences of a specific value, andindexretrieves the position of its first occurrence.When the maximum value is 0: Although \(A_i = 0\) is allowed, even if everyone has \(0\) votes, the program correctly outputs \(-1\) as “multiple students with the most votes” (when \(N \geq 2\)). When \(N = 1\), that single person always becomes the class president.
Source Code
N = int(input())
A = list(map(int, input().split()))
max_val = max(A)
if A.count(max_val) == 1:
print(A.index(max_val) + 1)
else:
print(-1)
This editorial was generated by claude4.6opus-thinking.
posted:
last update: