Official

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

gemini-3.5-flash-thinking

Overview

This problem asks us to find, given temperature data of length \(N\), the number of contiguous subarrays of length \(K\) that form a “mountain pattern” — one that strictly increases and then strictly decreases exactly once.

Since counting independently for each query would exceed the time limit, we take the approach of fixing the “peak” of the mountain and collectively aggregating the possible mountain lengths. By using second-order differences (an extension of the imos method), we can efficiently answer all queries in \(O(N + Q)\) time complexity.


Analysis

1. Naive Approach and Its Limitations

For each query \(K\), consider scanning all subarrays of length \(K\) (a total of \(N - K + 1\) subarrays) and checking whether each satisfies the mountain pattern. If checking a single subarray takes \(O(K)\), then per query it costs \(O(NK)\), and overall \(O(QN)\), which in the worst case requires more than \(10^{10}\) operations, resulting in TLE (Time Limit Exceeded).

2. Change of Perspective: Focusing on the “Peak” of the Mountain

Instead of exhaustively searching all subarrays, we focus on “which positions can serve as the peak of a mountain.”

Consider a mountain pattern with position \(p\) as its peak. For \(p\) to be a peak: - Temperatures must be consecutively increasing to the left of \(p\) - Temperatures must be consecutively decreasing to the right of \(p\)

Therefore, we precompute the following values for each position \(p\): - \(L[p]\): The maximum length of a strictly increasing consecutive subsequence ending at position \(p\) (not including \(p\) itself, i.e., the maximum length such that \(S_{p-L[p]} < \cdots < S_{p-1} < S_p\)) - \(R[p]\): The maximum length of a strictly decreasing consecutive subsequence starting at position \(p\) (not including \(p\) itself, i.e., the maximum length such that \(S_p > S_{p+1} > \cdots > S_{p+R[p]}\))

For example, if the sequence is \([10, 12, 15, 13, 11, 14]\) and \(p=3\) (value is \(15\)), then the left side has \(10 < 12 < 15\) so \(L[3] = 2\), and the right side has \(15 > 13 > 11\) so \(R[3] = 2\).

3. Number of Mountains of Length \(K\) Formed from Peak \(p\)

At peak \(p\), by choosing \(a\) elements from the left (\(1 \le a \le L[p]\)) and \(b\) elements from the right (\(1 \le b \le R[p]\)), we can form a mountain pattern of length \(K = a + b + 1\).

Let \(g_p(K)\) denote the number of \((a, b)\) pairs satisfying the condition for a given length \(K\). Let \(A = L[p], B = R[p]\), and assume \(A \le B\) without loss of generality. Then the number of patterns \(g_p(K)\) for each \(K\) is as follows:

  • When \(K < 3\) or \(K > A + B + 1\): \(0\)
  • When \(3 \le K \le A + 2\): \(K - 2\) (increases by \(1\) from \(1\) to \(A\))
  • When \(A + 2 < K \le B + 2\): \(A\) (constant)
  • When \(B + 2 < K \le A + B + 1\): \(A + B + 2 - K\) (decreases by \(1\) from \(A\) to \(1\))

When graphed, this forms a “trapezoid (or triangle)” shape:

Count g_p(K)
  ^
A |       +---------+
  |      /           \
  |     /             \
0 +----+----+---------+----+---> Length K
  0    3   A+2       B+2  A+B+1

The final answer \(f(K)\) for each \(K\) is the sum of these trapezoid functions \(g_p(K)\) over all \(p\): $\(f(K) = \sum_{p=1}^{N} g_p(K)\)$


Algorithm

To efficiently perform the “trapezoid-shaped additions” for all \(p\), we use second-order differences (an extension of the imos method).

1. Trapezoid Addition via Second-Order Differences

When we want to add a linear function (a line with constant slope) over an interval, by taking the second-order difference, we can replace it with additions/subtractions only at the breakpoints (points where the slope changes).

Focusing on slope changes of the trapezoid \(g_p(K)\), there are changes at the following 4 positions: 1. At \(K = 3\), the slope changes from \(0\) to \(+1\) \(\implies D2[3] \mathrel{+}= 1\) 2. At \(K = \min(A, B) + 3\), the slope changes from \(+1\) to \(0\) \(\implies D2[\min(A, B) + 3] \mathrel{-}= 1\) 3. At \(K = \max(A, B) + 3\), the slope changes from \(0\) to \(-1\) \(\implies D2[\max(A, B) + 3] \mathrel{-}= 1\) 4. At \(K = A + B + 3\), the slope changes from \(-1\) to \(0\) \(\implies D2[A + B + 3] \mathrel{+}= 1\)

We perform these additions at the 4 points for all \(p\).

2. Restoration via Prefix Sums

After all additions to \(D2\) are complete for every \(p\), we take the prefix sum twice to restore the original function \(f(K)\): 1. \(D[i] = D[i-1] + D2[i]\) (first prefix sum: obtain the slope at each point) 2. \(f[i] = f[i-1] + D[i]\) (second prefix sum: obtain the actual value \(f(K)\))

This allows us to compute the answers for all \(K\) in \(O(N)\) at once.


Complexity

  • Time Complexity: \(O(N + Q)\)
    • Building the arrays \(L\) and \(R\): \(O(N)\)
    • Adding to the second-order difference array \(D2\) for each peak \(p\): \(O(N)\)
    • Restoring \(f(K)\) via two prefix sums: \(O(N)\)
    • Answering each query in \(O(1)\), so \(O(Q)\) for all queries
  • Space Complexity: \(O(N)\)
    • The arrays \(L, R, D2, D, f\) all have size \(O(N)\) (the maximum index for \(D2\) etc. is around \(2N + 10\)).

Implementation Notes

  • Array Size: Since \(A + B + 3\) can be up to around \(2N + 3\), the difference array D2 and others need to be allocated with size around \(2N + 10\), not just \(N\).

  • Index Boundaries: A mountain pattern can only be formed (with \(K \ge 3\)) when \(L[p] \ge 1\) and \(R[p] \ge 1\), so we only process positions \(p\) satisfying this condition.

  • Fast I/O: Since \(N, Q \le 2 \times 10^5\) and input is large, in C++ we use cin.tie(NULL); ios_base::sync_with_stdio(false); to speed up input/output.

    Source Code

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    // Optimize standard I/O operations for competitive programming
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int N, Q;
    if (!(cin >> N >> Q)) return 0;

    vector<long long> S(N + 1);
    for (int i = 1; i <= N; ++i) {
        cin >> S[i];
    }

    // L[i] is the length of the strictly increasing sequence ending at i
    vector<int> L(N + 1, 0);
    for (int i = 2; i <= N; ++i) {
        if (S[i] > S[i - 1]) {
            L[i] = L[i - 1] + 1;
        } else {
            L[i] = 0;
        }
    }

    // R[i] is the length of the strictly decreasing sequence starting at i
    vector<int> R(N + 1, 0);
    for (int i = N - 1; i >= 1; --i) {
        if (S[i] > S[i + 1]) {
            R[i] = R[i + 1] + 1;
        } else {
            R[i] = 0;
        }
    }

    // The maximum possible index for the second difference array is 2 * N + 10
    int max_idx = 2 * N + 10;
    vector<long long> D2(max_idx, 0);

    for (int p = 1; p <= N; ++p) {
        if (L[p] >= 1 && R[p] >= 1) {
            int A = L[p];
            int B = R[p];
            int mn = min(A, B);
            int mx = max(A, B);
            
            // Add the second difference of the trapezoidal function
            D2[3] += 1;
            D2[mn + 3] -= 1;
            D2[mx + 3] -= 1;
            D2[A + B + 3] += 1;
        }
    }

    // Integrate once to get the first difference array
    vector<long long> D(max_idx, 0);
    for (int i = 1; i < max_idx; ++i) {
        D[i] = D[i - 1] + D2[i];
    }

    // Integrate again to get the actual function values f[K]
    vector<long long> f(max_idx, 0);
    for (int i = 1; i < max_idx; ++i) {
        f[i] = f[i - 1] + D[i];
    }

    // Answer each query in O(1) time
    for (int q = 0; q < Q; ++q) {
        int K;
        cin >> K;
        if (K < max_idx) {
            cout << f[K] << "\n";
        } else {
            cout << 0 << "\n";
        }
    }

    return 0;
}

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

posted:
last update: