A - 山脈のジグザグ / Zigzag of Mountain Range Editorial by admin Editorial for printing
Claude 4.6 Opus (Thinking)Overview
This problem asks you to count the number of positions where three consecutive points have elevations forming a “peak (goes up then down)” or a “valley (goes down then up)” pattern.
Analysis
When focusing on three consecutive points \(R_i, R_{i+1}, R_{i+2}\), a “zigzag” is a pattern where the middle point is a local maximum (peak) or a local minimum (valley).
Let’s look at a concrete example. For the elevation sequence [1, 3, 2, 4, 1]:
| \(i\) | \(R_i, R_{i+1}, R_{i+2}\) | Pattern | Zigzag? |
|---|---|---|---|
| 1 | 1, 3, 2 | Up→Down (peak) | ✅ |
| 2 | 3, 2, 4 | Down→Up (valley) | ✅ |
| 3 | 2, 4, 1 | Up→Down (peak) | ✅ |
The answer is 3.
In this problem, we only need to check the condition once for each \(i\) (\(1 \leq i \leq N-2\)), so a straightforward brute-force approach is sufficient. No special algorithms or data structures are needed.
Organizing the conditions, we check whether either of the following two conditions is satisfied:
- Peak: \(R_i < R_{i+1}\) and \(R_{i+1} > R_{i+2}\)
- Valley: \(R_i > R_{i+1}\) and \(R_{i+1} < R_{i+2}\)
Algorithm
- Read \(N\) and the elevation sequence \(R\) as input.
- Initialize a counter
countto \(0\). - For \(i = 0, 1, \ldots, N-3\) (0-indexed), check whether the three consecutive points \(R_i, R_{i+1}, R_{i+2}\) satisfy the peak or valley condition.
- If the condition is satisfied, increment
countby \(1\). - Output the final
count.
N = int(input())
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)
Inside the loop, we only perform a constant number of comparisons for each \(i\), making it very simple.
Complexity
- Time complexity: \(O(N)\) — just a single pass through the array
- Space complexity: \(O(N)\) — storing the elevation sequence as an array
Implementation Notes
Note that equality cases (such as \(R_i = R_{i+1}\)) are not included as zigzags. The conditions in the problem are defined using strict inequalities (
<and>).The loop range is
range(N - 2). By having \(i\) range from \(0\) to \(N-3\), we ensure that \(i+2\) does not go out of bounds of the array.Source Code
N = int(input())
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)
This editorial was generated by claude4.6opus-thinking.
posted:
last update: