A - 登山道の気温変化 / Temperature Changes on a Mountain Trail Editorial by admin
GPT 5.4 HighOverview
For each checkpoint \(i\), examine the absolute difference in temperature from the previous checkpoint \(i-1\), \(|T_i - T_{i-1}|\), and count it as a “sudden change” if this value is at least \(K\).
In other words, the answer can be found by simply looking at adjacent checkpoints in order.
Analysis
The key insight of this problem is that the only comparison needed is with the “immediately preceding checkpoint”.
The problem defines the condition for a sudden change at checkpoint \(i\) as:
\(|T_i - T_{i-1}| \geq K\)
Therefore, for each checkpoint \(i\), we only need to compare \(T_i\) and \(T_{i-1}\).
For example, if the temperatures are
\(10, 13, 5, 8\)
and \(K=4\), then:
- Checkpoint \(2\): \(|13-10|=3\) → not a sudden change
- Checkpoint \(3\): \(|5-13|=8\) → sudden change
- Checkpoint \(4\): \(|8-5|=3\) → not a sudden change
So the answer is \(1\).
Straightforward Approach
You can store all temperatures in an array and then compare sequentially from \(i=2\) to \(N\).
This approach is also \(O(N)\), which is fast enough.
However, upon further reflection, there is no need to store all temperatures at all.
Since we only need “the previous temperature”:
- Store the first temperature in
prev - Read the next temperature as
cur - If \(|cur-prev| \geq K\), increment the answer
- Update
prev = cur
Simply repeat this process.
Why This Is Sufficient
The determination for each checkpoint \(i\) depends only on \(T_i\) and \(T_{i-1}\).
Temperatures before that are not needed for the determination, so keeping only the previous value is sufficient.
With this approach, we can count the answer on the fly while reading the input.
Algorithm
- Read \(N, K\).
- Store the first temperature \(T_1\) in
prev. - For the remaining \(N-1\) temperatures, read each one as
cur. - If \(|cur - prev| \geq K\), increment the answer
ansby \(1\). - Update
prev = cur. - Output
ansat the end.
With this method, the answer is obtained by examining each temperature exactly once.
Complexity
- Time complexity: \(O(N)\)
- Space complexity: \(O(1)\)
Implementation Notes
The sudden change condition uses “greater than or equal to,” so the comparison should use
>=instead of>.Since we need the absolute value of the difference, use
abs(cur - prev).This implementation does not store temperatures in an array but processes them while keeping only the previous temperature, which minimizes memory usage.
Since the input can have up to \(10^5\) lines, in Python using
sys.stdin.readlineensures stable and fast reading.Source Code
import sys
def main():
input = sys.stdin.readline
N, K = map(int, input().split())
prev = int(input())
ans = 0
for _ in range(N - 1):
cur = int(input())
if abs(cur - prev) >= K:
ans += 1
prev = cur
print(ans)
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.4-high.
posted:
last update: