公式

A - クラス委員長の選出 / Election of the Class President 解説 by admin

gpt-5.3-codex

Overview

This is a problem of determining whether there is “exactly one” student with the maximum number of votes.
If the maximum vote count is unique, output that student’s number (1-indexed); if there are multiple students tied for first place, output \(-1\).

Analysis

The key insight is that the condition for becoming class president is determined not by the maximum value itself but by the number of times the maximum value appears.

  • First, find the maximum value \(mx\) of the vote count array \(A\)
  • Then count how many times \(mx\) appears
    • If it appears once, the student at that position becomes class president
    • If it appears two or more times, there is a tie for first place, so output \(-1\)

For example, if \(A = [3, 5, 2, 5]\), the maximum is \(5\) and there are 2 students with that value, so the answer is \(-1\).
If \(A = [1, 4, 2, 3]\), the maximum is \(4\) and only 1 student has it, so we output student number \(2\).

About the Naive Approach

If we check for each student whether there exists someone with more votes by scanning every time, this results in a double loop with \(O(N^2)\) complexity, which is too slow for \(N \le 2 \times 10^5\).
On the other hand, using max, count, and index each requires only a single pass through the array, so the entire solution runs in linear time.

Algorithm

  1. Read the input
  2. Find the maximum vote count with mx = max(A)
  3. Count the number of students with the maximum vote count using cnt = A.count(mx)
  4. If cnt == 1, output A.index(mx) + 1 (the problem uses 1-based indexing)
  5. Otherwise, output -1

Complexity

  • Time complexity: \(O(N)\)
    (max, count, and index are each \(O(N)\), and combined they are still \(O(N)\) with a constant factor)
  • Space complexity: \(O(N)\)
    (for storing the input array \(A\))

Implementation Notes

  • Student numbers are 1-indexed, so you need to add +1 to the result of index.

  • Using sys.stdin.readline provides faster input, which is suitable for competitive programming.

  • Due to the constraints, vote counts \(A_i\) can include 0, but the solution correctly handles the case even when the maximum value is 0.

    Source Code

import sys

def main():
    input = sys.stdin.readline
    N = int(input().strip())
    A = list(map(int, input().split()))
    
    mx = max(A)
    cnt = A.count(mx)
    
    if cnt == 1:
        print(A.index(mx) + 1)  # 1-indexed
    else:
        print(-1)

if __name__ == "__main__":
    main()

This editorial was generated by gpt-5.3-codex.

投稿日時:
最終更新: