B - 最初のアラート / First Alert Editorial by admin
Claude 4.5 OpusOverview
This problem asks you to find the number of the first log whose importance level is at least the threshold \(K\) among \(N\) logs.
Analysis
The Essence of the Problem
The key point of this problem is to find the log that satisfies the condition “first”.
- Once an alert is triggered, no further alerts are triggered after that
- In other words, even if there are multiple logs with importance level \(K\) or higher, only the first one is the answer
Understanding Through a Concrete Example
For example, when \(N = 5\), \(K = 50\), \(P = [30, 60, 40, 80, 70]\):
| Log Number | Importance | \(\geq K\)? |
|---|---|---|
| 1 | 30 | No |
| 2 | 60 | Yes ← Alert triggered here! |
| 3 | 40 | (Not checked due to ongoing response) |
| 4 | 80 | (Not checked due to ongoing response) |
| 5 | 70 | (Not checked due to ongoing response) |
The answer is 2.
A Naive Approach Is Sufficient
For this problem, we just need to scan from the beginning and find the first element that satisfies the condition. No special algorithm is required—a simple linear search will solve it.
Algorithm
- Examine the logs in order starting from the first one
- Compare each log’s importance level \(P_i\) with the threshold \(K\)
- When the first log satisfying \(P_i \geq K\) is found, output that log number and exit the loop
- If no log satisfies the condition until the end, output \(-1\)
result = -1 # Initial value is -1, representing "not found"
for i in range(N):
if P[i] >= K:
result = i + 1 # Convert from 0-indexed to 1-indexed
break # Exit immediately once the first one is found
print(result)
Complexity
- Time Complexity: \(O(N)\)
- In the worst case, we need to check all \(N\) logs
- However, if a log satisfying the condition is found early, we can terminate the search there
- Space Complexity: \(O(N)\)
- We store \(N\) elements in the array holding the importance levels of the logs
Implementation Notes
Be Careful with Index Conversion
- Python arrays are 0-indexed (starting from 0), but the problem statement asks for log numbers in 1-indexed format (starting from 1)
- Therefore, output
i + 1
Early Termination with
break- By exiting the loop immediately after finding the first match, we avoid unnecessary processing
- This makes the code run efficiently
Setting the Initial Value
By initializing the result variable to \(-1\) at the beginning, we can naturally handle the case where no log satisfies the condition
Source Code
N, K = map(int, input().split())
P = list(map(int, input().split()))
result = -1
for i in range(N):
if P[i] >= K:
result = i + 1
break
print(result)
This editorial was generated by claude4.5opus.
posted:
last update: