A - 山脈のジグザグ / Zigzag of Mountain Range Editorial by admin Editorial for printing
Gemini 3.0 Flash (Thinking)Overview
Given elevation data for \(N\) points, the problem asks us to find the total number of positions where three consecutive points form a “zigzag” pattern — either “going up then down” or “going down then up.”
Analysis
The “zigzag” condition required in this problem can be determined by looking only at three consecutive elements \(R_i, R_{i+1}, R_{i+2}\) — it is a “local condition.”
Specifically, we check whether one of the following two patterns is satisfied: 1. Peak (up then down): \(R_i < R_{i+1}\) and \(R_{i+1} > R_{i+2}\) 2. Valley (down then up): \(R_i > R_{i+1}\) and \(R_{i+1} < R_{i+2}\)
Note that cases where elevations are equal (such as \(R_i = R_{i+1}\)) are not considered zigzag.
Looking at the constraints, \(N\) can be up to \(2 \times 10^5\), so an \(O(N)\) algorithm that scans the list once from one end to the other will comfortably fit within the time limit.
Algorithm
- Read the list of elevations \(R\).
- Initialize a variable
countto \(0\) to count the number of zigzags. - Iterate index \(i\) from \(0\) to \(N-3\), performing the following at each step:
- Check whether \(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 value of
count.
Complexity
- Time complexity: \(O(N)\)
- Since we examine each element of the list once in order, the computation finishes in time proportional to \(N\).
- Space complexity: \(O(N)\)
- This is the memory required to store the \(N\) elevation data points in a list.
Implementation Notes
Loop range: Since we look at three consecutive elements, the starting index \(i\) goes up to the \((N-2)\)-th point (i.e., index \(N-3\)). Using Python’s
range(n - 2)makes \(i\) range from \(0\) to \(n-3\), so \(i+2\) reaches at most \(n-1\) (the last element), preventing index-out-of-range errors.Fast I/O: Since \(N\) can be large, in Python using
sys.stdin.read().split()or similar methods to read all input at once can reduce execution time.Source Code
import sys
def solve():
# 入力の読み込み
input_data = sys.stdin.read().split()
if not input_data:
return
n = int(input_data[0])
r = list(map(int, input_data[1:]))
count = 0
# 連続する3つの地点 (i, i+1, i+2) について判定を行う
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__":
solve()
This editorial was generated by gemini-3-flash-thinking.
posted:
last update: