公式

E - 最短の棒が二本ある区間 / Intervals with Two Shortest Sticks 解説 by admin

claude5.5opus-high

Overview

This problem asks us to count the number of subarrays where the minimum value \(m\) appears exactly \(2\) times, and every value in the subarray is a multiple of \(m\). We fix the pair of two positions where the minimum value \(m\) appears, and find the number of valid subarrays containing this pair using multiplication.

Analysis

Rephrasing the Condition

“All sticks can be cut into sticks of length \(m\) without remainder” means that all values in the subarray are multiples of \(m\).

Furthermore, the following holds:

  • If all values in the subarray are multiples of some value \(a\) present in the subarray, then every value is at least \(a\). Therefore, the minimum value automatically becomes \(a\).

Thus, the condition can be rephrased as follows:

A certain value \(a\) appears exactly \(2\) times in the subarray, and all values in the subarray are multiples of \(a\).

Counting by Pairs

In a subarray that satisfies the condition, the two positions \(p < q\) where the minimum value \(a\) appears are uniquely determined. Also, since \(a\) appears exactly \(2\) times in the subarray, \(q\) must be the next occurrence of \(a\) after \(p\).

Therefore, we enumerate all pairs of positions \((p, q)\) where the same value appears consecutively (\(q\) is the next occurrence of \(A_p\) after \(p\)). For each pair, if we count the number of subarrays \([L, R]\) where these two are the two minimum elements and sum them up, we can count without duplicates or omissions.

Range of the Subarray Endpoints

Fix the pair \((p, q)\) and \(a = A_p\).

  • \(r\): the first position to the right of \(p\) that is not a multiple of \(a\) (or \(N\) if none exists)
  • \(l\): the first position to the left of \(p\) that is not a multiple of \(a\) (or \(-1\) if none exists)
  • \(\text{prv}_p\): the position where \(a\) appears before \(p\) (or \(-1\) if none exists)
  • \(\text{nxt}_q\): the position where \(a\) appears after \(q\) (or \(N\) if none exists)

First, unless \(q < r\), there is a value between \(p\) and \(q\) that is not a multiple of \(a\), so no valid subarray can be formed from this pair.

When \(q < r\), the subarray \([L, R]\) must satisfy the following two conditions:

  • Does not contain any value that is not a multiple of \(a\)
  • Does not contain \(3\) or more occurrences of \(a\)

From this, the ranges of the endpoints are as follows:

  • Range of \(L\): \(\max(l, \text{prv}_p) < L \le p\)
  • Range of \(R\): \(q \le R < \min(r, \text{nxt}_q)\)

Since \(L\) and \(R\) can be chosen independently, the number of valid subarrays is the following product: $\((p - \max(l,\text{prv}_p)) \times (\min(r,\text{nxt}_q) - q)\)$

Concrete Example

Consider the case where \(A = [2,4,2,6,2]\) (0-indexed).

Pair \(l\) \(r\) Range of left endpoint Range of right endpoint Count
\((0,2)\) \(-1\) \(5\) From \(\max(-1,-1)=-1\), \(L\in\{0\}\) From \(\min(5,4)=4\), \(R\in\{2,3\}\) \(1\times2=2\)
\((2,4)\) \(-1\) \(5\) From \(\max(-1,0)=0\), \(L\in\{1,2\}\) From \(\min(5,5)=5\), \(R\in\{4\}\) \(2\times1=2\)

The total is \(4\).

Issues with the Naive Approach

Checking all \(O(N^2)\) subarrays will result in TLE when \(N = 200000\). While enumerating pairs only takes \(O(N)\), searching for \(l\) and \(r\) by stepping through elements one by one would take \(O(N^2)\) in the worst case.

Key to Speedup

“All elements in the subarray are multiples of \(a\)” is equivalent to “the \(\gcd\) of the subarray is divisible by \(a\)”. The range \(\gcd\) can be queried in \(O(1)\) using a Sparse Table. Furthermore, since the property of “being a multiple” only breaks as the interval is extended (monotonicity), we can find \(r\) and \(l\) in \(O(\log N)\) using doubling (binary search).

Algorithm

  1. Build a Sparse Table for gcd. sp[k][i] represents the \(\gcd\) of \(A_i, \dots, A_{i+2^k-1}\).
  2. Find the previous and next occurrences of the same value for each position. Record the most recent occurrence position for each value using a dictionary to compute prv[i] and nxt[i].
  3. For each \(p\), if \(q = \text{nxt}_p\) exists, perform the following:
    • Rightward direction: Start from pos = p+1 and try \(k\) in descending order. If sp[k][pos] is divisible by \(a\), set pos += 2^k. The final pos is \(r\).
    • If \(q \ge r\), skip this pair.
    • Leftward direction: Similarly, if sp[k][pos-2^k+1] is divisible by \(a\), set pos -= 2^k to find \(l\).
    • Add \((p - \max(l, \text{prv}_p)) \times (\min(r, \text{nxt}_q) - q)\) to the answer.
  4. Output the total sum.

Complexity

  • Time Complexity: \(O(N \log N \cdot \log A)\)
    • Computing \(\gcd\) \(O(N \log N)\) times during Sparse Table construction.
    • Doubling for each pair requires only \(O(\log N)\) modulo operations.
  • Space Complexity: \(O(N \log N)\) (for the Sparse Table)

Implementation Notes

  • Order of doubling: Try \(k\) in descending order. Greedily extending whenever “extending still satisfies the condition (all elements are multiples of \(a\))” finds the maximal valid range. Be sure to check conditions like pos + 2^k <= n or st >= 0 to prevent out-of-bounds access.

  • Excluding a third \(a\): Since \(a\) itself is a multiple of \(a\), \(l\) and \(r\) alone cannot exclude subarrays containing a third \(a\). Always restrict the endpoints using \(\text{prv}_p\) and \(\text{nxt}_q\) as well.

  • Speedup in Python: Sparse Table construction is faster when batch-processed using map(gcd, ...) and slicing. Also, precomputing powers of \(2\) into a list can reduce computations inside loops.

  • Magnitude of the answer: The answer can be up to around \(O(N^2)\). In Python, integer overflow is not a concern.

    Source Code

import sys
from math import gcd

def main():
    data = sys.stdin.buffer.read().split()
    n = int(data[0])
    A = list(map(int, data[1:1+n]))
    # sparse table of gcd
    sp = [A]
    k = 1
    while (1 << k) <= n:
        prev = sp[-1]
        h = 1 << (k - 1)
        ln = n - (1 << k) + 1
        cur = list(map(gcd, prev[:ln], prev[h:h+ln]))
        sp.append(cur)
        k += 1
    LOG = len(sp)
    # next / prev occurrence
    nxt = [n] * n
    prv = [-1] * n
    last = {}
    for i in range(n):
        v = A[i]
        if v in last:
            j = last[v]
            prv[i] = j
            nxt[j] = i
        last[v] = i
    ks = list(range(LOG - 1, -1, -1))
    pw = [1 << k for k in range(LOG)]
    ans = 0
    for p in range(n):
        q = nxt[p]
        if q >= n:
            continue
        a = A[p]
        # right: first non-multiple after p
        pos = p + 1
        for k in ks:
            s = pw[k]
            if pos + s <= n and sp[k][pos] % a == 0:
                pos += s
        r = pos
        if q >= r:
            continue
        # left
        pos = p - 1
        for k in ks:
            s = pw[k]
            st = pos - s + 1
            if st >= 0 and sp[k][st] % a == 0:
                pos -= s
        l = pos
        pp = prv[p]
        lb = l if l > pp else pp
        q2 = nxt[q]
        rb = r if r < q2 else q2
        ans += (p - lb) * (rb - q)
    print(ans)

main()

This editorial was generated by claude5.5opus-high.