公式

E - 山型の気温パターンを数えよ / Count Mountain-Shaped Temperature Patterns 解説 by admin

gemini-3.5-flash-thinking

Overview

This problem asks us to determine, for each query, how many “mountain-shaped patterns” of a specified length \(K\) exist within temperature data of length \(N\).

By organizing the range and count of mountain-shaped patterns that can be formed when each position is considered as the “peak,” we can efficiently answer all queries at once using second-order difference arrays (second-order imos method).


Analysis

1. Naive Approach and Its Limitations

To count mountain-shaped patterns of length \(K\), if we naively check whether a valid peak \(p\) exists for every starting position \(l\) (\(1 \leq l \leq N-K+1\)), it takes \(O(N \cdot K)\) or \(O(N^2)\) time per query. Since the number of queries \(Q\) can also be up to \(N\), the total time complexity becomes \(O(Q \cdot N^2)\), which exceeds the time limit (TLE).

To speed things up, instead of thinking in terms of “starting positions of mountain-shaped patterns,” we take the approach of fixing the “peak position \(i\)” as our reference point.

2. Fixing the Peak

Consider a mountain-shaped pattern with position \(i\) as its peak. The left side of position \(i\) must be strictly increasing, and the right side must be strictly decreasing.

We precompute the following two values: - \(L[i]\): The maximum length of a strictly increasing consecutive subsequence ending at position \(i\) - \(R[i]\): The maximum length of a strictly decreasing consecutive subsequence starting at position \(i\)

For a mountain-shaped pattern with peak at position \(i\): - Let the length of the increasing part on the left be \(x\) (\(1 \leq x \leq L[i] - 1\)) - Let the length of the decreasing part on the right be \(y\) (\(1 \leq y \leq R[i] - 1\))

Then the length \(K\) of this mountain-shaped pattern can be expressed as \(K = x + y + 1\). For a valid mountain-shaped pattern, at least one step is needed on each side, so the condition is \(L[i] \geq 2\) and \(R[i] \geq 2\).

3. Efficiently Aggregating Combination Counts for \(K\) (Second-Order Imos Method)

When the peak \(i\) is fixed, we can freely choose \(x \in [1, L[i]-1]\) and \(y \in [1, R[i]-1]\). The number of combinations for the mountain-shaped pattern length \(K = x + y + 1\) varies with \(K\) as follows:

For simplicity, let \(A = \min(L[i], R[i]) - 1\) and \(B = \max(L[i], R[i]) - 1\). The range of possible \(K\) values is \(3 \leq K \leq L[i] + R[i] - 1\), and the combination count changes as \(K\) increases as follows: - Increasing phase: As \(K\) increases from \(3\), the combination count increases by \(1\) each time: \(1, 2, 3, \ldots, A\). - Flat phase: For a while, the combination count remains constant at \(A\). - Decreasing phase: After that, the combination count decreases by \(1\) each time: \(A-1, A-2, \ldots, 1, 0\).

Thus, the graph of combination counts forms a “trapezoid (or triangle)” shape. Operations like “adding values that change linearly over an interval” can be processed in \(O(1)\) per peak using second-order difference arrays (second-order imos method).

Understanding Through a Concrete Example

Consider the case where \(L[i] = 3, R[i] = 4\). Here, \(x \in [1, 2], y \in [1, 3]\). The combination counts for \(K = x + y + 1\) are as follows: - \(K = 3\): \((x, y) = (1, 1)\) — \(1\) way - \(K = 4\): \((x, y) = (1, 2), (2, 1)\) — \(2\) ways - \(K = 5\): \((x, y) = (1, 3), (2, 2)\) — \(2\) ways - \(K = 6\): \((x, y) = (2, 3)\) — \(1\) way - \(K \geq 7\): \(0\) ways

To construct the addition values [0, 0, 0, 1, 2, 2, 1, 0, 0] for each \(K\), we prepare a second-order difference array dd. Setting \(a = \min(L[i], R[i]) + 1 = 4\), \(b = \max(L[i], R[i]) + 1 = 5\), \(c = L[i] + R[i] + 1 = 8\), we add values at the following 4 positions: - dd[3] += 1 - dd[a + 1] -= 1 (in this case dd[5] -= 1) - dd[b + 1] -= 1 (in this case dd[6] -= 1) - dd[c] += 1 (in this case dd[8] += 1)

Applying prefix sums twice to this dd yields:

  1. First prefix sum D: [0, 0, 0, 1, 1, 0, -1, -1, 0] (represents changes in slope)
  2. Second prefix sum g: [0, 0, 0, 1, 2, 2, 1, 0, 0] (represents the actual addition values)

We can confirm this perfectly matches the desired combination counts. By performing the additions to dd in \(O(1)\) for all peaks \(i\), and then taking prefix sums twice at the end, we can compute the total number of mountain-shaped patterns for all \(K\) in \(O(N)\).


Algorithm

  1. Construction of arrays \(L, R\):
    • Scan from left to right: if \(S[i] > S[i-1]\), then \(L[i] = L[i-1] + 1\); otherwise \(L[i] = 1\).
    • Scan from right to left: if \(S[i] > S[i+1]\), then \(R[i] = R[i+1] + 1\); otherwise \(R[i] = 1\).
  2. Recording second-order differences:
    • Initialize a difference array dd of size \(N + 5\) with zeros.
    • For each \(i\) (\(0 \leq i < N\)), if \(L[i] \geq 2\) and \(R[i] \geq 2\), perform dd[3] += 1, dd[a+1] -= 1, dd[b+1] -= 1, dd[c] += 1 as described above.
  3. Computing prefix sums:
    • Take the prefix sum of dd to obtain array D.
    • Take the prefix sum of D to obtain array g. Now g[K] gives the total number of mountain-shaped patterns of length \(K\).
  4. Answering queries:
    • For each query \(K_j\), output g[K_j].

Complexity

  • Time complexity: \(O(N + Q)\)

    • Construction of \(L, R\) takes \(O(N)\) time.
    • Adding to dd for each peak takes \(O(N)\) time.
    • Computing prefix sums (twice) takes \(O(N)\) time.
    • Answering each query takes \(O(1)\), so all queries take \(O(Q)\) time in total.
    • Therefore, the overall time complexity is \(O(N + Q)\), which comfortably fits within the time limit.
  • Space complexity: \(O(N)\)

    • We maintain several arrays of size \(N\) (\(L, R, dd, D, g\), etc.), so the space complexity is \(O(N)\).

Implementation Notes

  • Array size:

    • When adding to dd, indices such as a + 1, b + 1, c may exceed \(N\). To prevent IndexError, the array size should be allocated slightly larger, such as \(N + 5\).
  • Fast I/O:

    • When handling input/output with \(N, Q \le 2 \times 10^5\) in Python, reading all input at once using sys.stdin.read can eliminate I/O bottlenecks.

      Source Code

import sys


def solve():
    input = sys.stdin.read
    data = input().split()
    if not data:
        return
    N = int(data[0])
    Q = int(data[1])
    S = [int(x) for x in data[2 : 2 + N]]
    queries = [int(x) for x in data[2 + N : 2 + N + Q]]

    L = [1] * N
    for i in range(1, N):
        if S[i] > S[i - 1]:
            L[i] = L[i - 1] + 1

    R = [1] * N
    for i in range(N - 2, -1, -1):
        if S[i] > S[i + 1]:
            R[i] = R[i + 1] + 1

    dd = [0] * (N + 5)
    for i in range(N):
        l = L[i]
        r = R[i]
        if l >= 2 and r >= 2:
            if l < r:
                a = l + 1
                b = r + 1
            else:
                a = r + 1
                b = l + 1
            c = l + r + 1
            dd[3] += 1
            dd[a + 1] -= 1
            dd[b + 1] -= 1
            dd[c] += 1

    D = [0] * (N + 5)
    cur = 0
    for i in range(N + 5):
        cur += dd[i]
        D[i] = cur

    g = [0] * (N + 5)
    cur = 0
    for i in range(N + 5):
        cur += D[i]
        g[i] = cur

    ans = [str(g[K]) for K in queries]
    print("\n".join(ans))


if __name__ == "__main__":
    solve()

This editorial was generated by gemini-3.5-flash-thinking.