公式

A - 的当てゲーム / Target Shooting Game 解説 by admin

gemini-3-flash-thinking

Overview

There are \(N\) balls, and the weight \(D_i\) of each ball directly corresponds to its flight distance. The problem asks how many balls have a flight distance within the range from \(L-W\) to \(L+W\) inclusive.

Analysis

The most important aspect of this problem is organizing the condition for “a ball hitting the target” into a mathematical expression.

From the problem statement, the conditions for a ball with weight \(D_i\) to hit the target are: - The distance from Takahashi is at least \(L-W\) - The distance from Takahashi is at most \(L+W\)

Combining these into a single inequality gives \(L-W \leq D_i \leq L+W\).

Since each ball can be evaluated independently, we can obtain the correct answer by sequentially checking whether this inequality holds for every ball.

Looking at the constraints, the number of balls \(N\) is at most \(2 \times 10^5\). A straightforward approach of checking each ball one by one (\(O(N)\)) results in approximately \(2 \times 10^5\) operations, which is well within the time limit.

Algorithm

The solution is obtained through the following steps:

  1. Compute the lower bound \(L-W\) and upper bound \(L+W\) of the hitting range, and store them in variables (lower_bound, upper_bound).
  2. Initialize a variable count to \(0\) to track the number of balls that hit the target.
  3. For each ball’s weight \(D_i\), repeat the following process:
    • If \(lower\_bound \leq D_i\) and \(D_i \leq upper\_bound\), add \(1\) to count.
  4. Output the final value of count.

Complexity

  • Time complexity: \(O(N)\)
    • Since each of the \(N\) balls is checked exactly once, the time is proportional to \(N\).
  • Space complexity: \(O(N)\)
    • If the \(N\) input weights are stored as a list, the memory usage is proportional to \(N\).

Implementation Notes

  • Fast I/O: Since \(N\) can be as large as \(2 \times 10^5\), in Python it is more efficient to read all input at once using sys.stdin.read().split() rather than calling input() repeatedly, which reduces execution time.

  • Range check syntax: In Python, you can write range checks intuitively in a form close to mathematical inequalities, such as lower_bound <= d <= upper_bound.

    Source Code

import sys

def solve():
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    
    n = int(input_data[0])
    l = int(input_data[1])
    w = int(input_data[2])
    d_list = input_data[3:]
    
    lower_bound = l - w
    upper_bound = l + w
    
    count = 0
    for i in range(n):
        d = int(d_list[i])
        if lower_bound <= d <= upper_bound:
            count += 1
            
    print(count)

if __name__ == '__main__':
    solve()

This editorial was generated by gemini-3-flash-thinking.

投稿日時:
最終更新: