B - 最初のアラート / First Alert 解説 by admin
GPT 5.2 HighOverview
We look through the logs from the beginning in order, and output the log number \(i\) where the importance \(P_i\) first reaches or exceeds the threshold \(K\). If no such log exists by the end, we output \(-1\).
Analysis
- The alert is triggered only once, at the first moment when \(P_i \ge K\), and everything after that is ignored.
- In other words, the answer we seek is the smallest \(i\) satisfying the condition \(P_i \ge K\).
- Due to this property, we can scan the logs in order and immediately determine the answer as soon as the condition is met (there is no need to examine the rest).
Concrete example: - When \(N=5, K=10, P=[3, 8, 10, 12, 1]\), the condition is first satisfied at the 3rd log where \(P_3=10 \ge 10\), so the answer is \(3\).
A naive approach such as “collect all positions that satisfy the condition and take the minimum” is also possible, but it still requires a full scan. In this case, terminating as soon as the first match is found is the simplest and fastest approach.
Algorithm
- Examine array \(P\) sequentially from \(i=1\) to \(N\).
- If \(P_i \ge K\), output \(i\) at that point and terminate.
- If no match is found after examining all elements, output \(-1\).
Complexity
- Time complexity: \(O(N)\) (in the worst case, each log is checked exactly once)
- Space complexity: \(O(1)\) (excluding the input array, only a constant amount of additional space is needed)
Implementation Notes
1-indexed (log numbers start from 1), so use something like
enumerate(P, 1)to start the index at 1.Immediately
returnwhen the condition is met to exit early (avoiding unnecessary scanning).Since the input size can be large, using
sys.stdin.buffer.read()in Python allows for faster input reading.Source Code
import sys
def main():
data = list(map(int, sys.stdin.buffer.read().split()))
N, K = data[0], data[1]
P = data[2:2+N]
for i, x in enumerate(P, 1):
if x >= K:
print(i)
return
print(-1)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.
投稿日時:
最終更新: