A - 山脈のジグザグ / Zigzag of Mountain Range Editorial by admin Editorial for printing
DeepSeek V3Overview
This problem asks you to count how many “zigzag” patterns (three consecutive points that go up then down, or down then up) exist in a given sequence of elevations.
Approach
Following the problem’s definition, for each set of three consecutive points \((i, i+1, i+2)\), we simply check whether either of the following two conditions is satisfied: 1. \(R_i < R_{i+1}\) and \(R_{i+1} > R_{i+2}\) (goes up then down) 2. \(R_i > R_{i+1}\) and \(R_{i+1} < R_{i+2}\) (goes down then up)
The problem can be solved by performing this check for all possible sets of three consecutive points (\(i\) from \(1\) to \(N-2\)). Since the constraint is \(N \leq 2 \times 10^5\), a simple loop is fast enough.
Algorithm
- Read the number of points \(N\) and the elevation list \(R\)
- Loop from \(i = 0\) to \(N-3\) (0-indexed)
- For each \(i\), check whether condition 1 or condition 2 is satisfied
- If the condition is satisfied, increment the counter by 1
- Output the final value of the counter
Complexity
- Time complexity: \(O(N)\)
- Each step in the loop of \(N-2\) iterations takes constant time, so the overall complexity is \(O(N)\)
- Space complexity: \(O(N)\)
- Memory to store the elevation list
Implementation Notes
Be careful with the loop range: with 0-indexing, \(i\) goes from \(0\) to \(n-3\) (\(n-2\) iterations)
Write the conditions accurately: correctly combine the logical operator
andwith comparison operatorsInput reading: use
map(int, input().split())for efficient readingSource Code
def main():
n = int(input().strip())
R = list(map(int, input().split()))
count = 0
for i in range(n - 2):
if (R[i] < R[i+1] and R[i+1] > R[i+2]) or (R[i] > R[i+1] and R[i+1] < R[i+2]):
count += 1
print(count)
if __name__ == "__main__":
main()
This editorial was generated by deepseekv3.
posted:
last update: