E - 山型の気温パターンを数えよ / Count Mountain-Shaped Temperature Patterns Editorial by admin
GPT 5.2 HighOverview
For each query \(K\), we count the number of contiguous subarrays of length \(K\) that form a “mountain” pattern — strictly increasing up to some peak, then strictly decreasing after that peak.
Naively checking each \(K\) would be too slow, so instead we aggregate “how many mountain patterns of each length exist for each position as the peak.”
Analysis
Reformulating the Mountain Condition
An interval \([l, r]\) (of length \(K=r-l+1\)) is a mountain if there exists a peak \(p\) (\(l<p<r\)) such that: - Left side: \(S_l < S_{l+1} < \cdots < S_p\) (strictly increasing) - Right side: \(S_p > S_{p+1} > \cdots > S_r\) (strictly decreasing)
In other words, a mountain is determined entirely by “given a peak \(p\), how far can we extend to the left and to the right.”
Why a Naive Solution is Too Slow
- For each \(K\), checking all \(O(N)\) intervals and verifying whether each is a mountain in \(O(K)\) gives \(O(NK)\).
- Even with efficient checking, “\(O(N)\) per \(K\)” with up to \(Q=2\times 10^5\) queries results in \(O(NQ)\), which is too slow.
Solution Strategy: Accumulate Each Peak’s Contribution by Length \(K\)
- For each position \(i\) as a peak, count how many mountains of each length \(K\) it contributes to.
- Sum over all peaks to build \(ans[K]\) (the number of mountains of length \(K\)) for \(K=1..N\) all at once.
- For each query, simply output \(ans[K_j]\).
The key insight is that the number of mountains a single peak can form, as a function of \(K\), has a “trapezoidal shape” (increasing → constant → decreasing), which can be efficiently aggregated using interval linear function additions.
Algorithm
1. Precompute Consecutive Increasing/Decreasing Lengths
- \(inc[i]\): length of the strictly increasing consecutive subsequence ending at \(i\)
Example: if \(S[i-1] < S[i]\) then \(inc[i]=inc[i-1]+1\), otherwise \(1\). - \(dec[i]\): length of the strictly decreasing consecutive subsequence starting at \(i\)
Example: if \(S[i] > S[i+1]\) then \(dec[i]=dec[i+1]+1\), otherwise \(1\).
With this, when position \(i\) is the peak: - It can extend at most \(A=inc[i]\) positions to the left (including the peak) - It can extend at most \(B=dec[i]\) positions to the right (including the peak)
A mountain requires at least one step of increase on the left and one step of decrease on the right, so the necessary condition is \(A\ge 2\) and \(B\ge 2\).
2. Number of Contributions of Peak \(i\) to Length \(K\)
Fixing peak \(i\), let: - \(x\) = length of the left side (including peak) … \(2 \le x \le A\) - \(y\) = length of the right side (including peak) … \(2 \le y \le B\)
Then the total interval length is: $\(K = x + y - 1\)\( (subtracting \)1$ because the peak is counted in both sides)
So the number of mountains of length \(K\) is the number of pairs \((x,y)\) satisfying: $\(x+y = K+1,\quad 2\le x\le A,\ 2\le y\le B\)$
Setting $\(a=A-2,\quad b=B-2\quad(\ge 0)\)\( and substituting \)t=x-2,\ u=y-2\(: - \)0\le t\le a\( - \)0\le u\le b\( - \)t+u = K-3$
This is “the number of pairs from \([0,a]\) and \([0,b]\) that sum to a given value,” so as a function of \(K\): - First it increases as \(1,2,3,\dots\) - Then it stays constant - Then it decreases as \(\dots,3,2,1\)
This forms a trapezoid (or triangle in some cases).
Specifically, let $\(m=\min(a,b),\ M=\max(a,b),\ s=a+b\)$ then the contribution splits into three intervals (as noted in the code comments):
Increasing interval: \(K \in [3,\ 3+m]\)
$\(count(K)=K-2\)$Constant interval (when \(M>m\)): \(K \in [4+m,\ 3+M]\)
$\(count(K)=m+1\)$Decreasing interval (when \(s>M\)): \(K \in [4+M,\ 3+s]\)
$\(count(K)=(s+4)-K\)$
3. Accumulating “Interval Linear Functions” Using Difference Arrays
Directly updating \(ans[K]\) would be \(O(N^2)\) in the worst case.
Instead, we manage the operation of adding a linear function
$\(f(K)=c_1K+c_0\)\(
over an interval \)[L,R]$ using difference arrays for the coefficients.
- \(da\): difference array for \(c_1\) (coefficient of \(K\))
- \(db\): difference array for \(c_0\) (constant term)
Interval addition is done as: - \(da[L]+=c_1,\ da[R+1]-=c_1\) - \(db[L]+=c_0,\ db[R+1]-=c_0\)
Then, scanning \(K=1..N\) and taking prefix sums gives the current coefficients \((acoef,bcoef)\), from which: $\(ans[K]=acoef\cdot K + bcoef\)$
For each peak \(i\), we add the three intervals above using add_linear, sum over all peaks to build \(ans[1..N]\), and answer each query by outputting \(ans[K_j]\).
Complexity
- Time complexity: \(O(N)\)
(\(inc/dec\) computation is \(O(N)\), each peak’s processing involves a constant number of interval additions, and the final prefix sum scan is \(O(N)\)) - Space complexity: \(O(N)\)
(\(inc, dec, da, db, ans\), etc.)
Implementation Notes
A mountain requires at least one step on each side, so peak \(i\) only contributes when \(inc[i]\ge 2\) and \(dec[i]\ge 2\).
The contribution interval for a peak may be empty, so
add_linear(L,R,...)should skip when \(L>R\).By maintaining coefficients in difference arrays, we can compute the superposition of many trapezoids (interval linear functions) in \(O(N)\).
Source Code
import sys
def main():
it = list(map(int, sys.stdin.buffer.read().split()))
if not it:
return
idx = 0
N = it[idx]; idx += 1
Q = it[idx]; idx += 1
S = it[idx:idx+N]; idx += N
queries = it[idx:idx+Q]
inc = [1] * N
for i in range(1, N):
if S[i - 1] < S[i]:
inc[i] = inc[i - 1] + 1
dec = [1] * N
for i in range(N - 2, -1, -1):
if S[i] > S[i + 1]:
dec[i] = dec[i + 1] + 1
da = [0] * (N + 5) # diff for coefficient of K
db = [0] * (N + 5) # diff for constant term
def add_linear(L, R, c1, c0):
if L > R:
return
da[L] += c1
db[L] += c0
da[R + 1] -= c1
db[R + 1] -= c0
# For each peak i, A=inc[i], B=dec[i]
# Let a=A-2, b=B-2 (>=0). For K, contribution is a trapezoid.
for i in range(N):
A = inc[i]
B = dec[i]
if A < 2 or B < 2:
continue
a = A - 2
b = B - 2
m = a if a < b else b
M = b if a < b else a
s = a + b
# Increasing part: K in [3, 3+m], value = K-2
add_linear(3, 3 + m, 1, -2)
# Flat part: K in [4+m, 3+M], value = m+1
if M > m:
add_linear(4 + m, 3 + M, 0, m + 1)
# Decreasing part: K in [4+M, 3+s], value = (s+4) - K
if s > M:
add_linear(4 + M, 3 + s, -1, s + 4)
ans = [0] * (N + 1)
acoef = 0
bcoef = 0
for K in range(1, N + 1):
acoef += da[K]
bcoef += db[K]
ans[K] = acoef * K + bcoef
out = []
for K in queries:
out.append(str(ans[K]))
sys.stdout.write("\n".join(out))
if __name__ == "__main__":
main()
This editorial was generated by gpt-5.2-high.