Official

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

gpt-6-astra-medium

Overview

A subarray that satisfies the condition can be rephrased as “a subarray where the value equal to the greatest common divisor of the subarray appears exactly \(2\) times within it.” We can count these efficiently by sweeping the right endpoint and maintaining contiguous ranges of left endpoints that yield the same greatest common divisor.

Analysis

1. Rephrasing the Condition Using the Greatest Common Divisor

Let \(m\) be the minimum value of the subarray, and let \(g\) be the greatest common divisor of all its elements.

The condition that all sticks can be cut into pieces of length \(m\) without remainder means that every element is a multiple of \(m\). Furthermore, since the subarray contains the value \(m\) itself, we must have \(g = m\).

Conversely, if the subarray contains an element equal to the greatest common divisor \(g\), since all elements are positive multiples of \(g\), the minimum value is also \(g\).

Therefore, the condition we are looking for is equivalent to the following:

Letting \(g\) be the greatest common divisor of the subarray, the value \(g\) appears exactly \(2\) times in the subarray.

Knowing the greatest common divisor alone is not enough; we also need to check the number of occurrences of that value.

2. Grouping Subarrays with the Same Greatest Common Divisor

Since there are \(O(N^2)\) subarrays in total, checking them one by one will not run in time.

Thus, we fix the right endpoint \(i\) and consider the greatest common divisor as the left endpoint \(l\) varies.

When expanding the subarray by moving the left endpoint from right to left, the new greatest common divisor will be a divisor of the previous greatest common divisor. Whenever the value changes, it decreases to at most half of its previous value.

Therefore, letting \(M = \max A_i\), there are only \(O(\log M)\) distinct greatest common divisor values for a fixed right endpoint.

Moreover, the left endpoints that yield the same greatest common divisor form contiguous ranges. Hence, we can manage them in groups by ranges of left endpoints.

3. Determining “Exactly \(2\) Occurrences” from Positions

Let \(p_1, p_2, p_3\) be the positions where the value \(g\) appears at or to the left of the right endpoint \(i\), in reverse chronological order (most recent first). If a position does not exist, let it be \(-1\). The indices are \(0\)-based, consistent with code implementations.

The condition for the subarray \([l, i]\) to contain the value \(g\) exactly \(2\) times is that:

  • It contains the second most recent occurrence \(p_2\).
  • It does not contain the third most recent occurrence \(p_3\).

This means \(p_3 < l \le p_2\).

Therefore, it is sufficient to remember only the last \(3\) occurrence positions for each value.

Algorithm

We process the right endpoint \(i\) in order from \(0\) to \(N-1\).

1. Updating the Occurrence Positions

We maintain the last \(3\) occurrence positions of each value using a dictionary history.

Let the current value be \(a = A_i\). If the previous record was \((p_1, p_2, p_3)\), we update it to \((i, p_1, p_2)\). If it appears for the first time, we set it to \((i, -1, -1)\).

2. Updating the Greatest Common Divisor Groups

We maintain the following two arrays:

  • gcds[j]: The greatest common divisor of group \(j\)
  • starts[j]: The minimum position of the left endpoints belonging to that group

The groups are ordered by increasing left endpoint positions. The range of left endpoints represented by group \(j\) is \([\text{starts}[j], \text{starts}[j+1]-1]\) if a next group exists, or \([\text{starts}[j], i]\) if it is the last group.

When advancing the right endpoint from \(i-1\) to \(i\), each previous greatest common divisor \(g\) becomes \(\gcd(g, a)\).

We update all groups and merge adjacent groups whenever their greatest common divisors become identical. Finally, we append the length-\(1\) subarray \([i, i]\). However, if the greatest common divisor of the last group is already \(a\), it can simply be included in that group.

3. Counting Valid Left Endpoints in Each Group

Let \(g\) be the greatest common divisor of a group, and let its range of left endpoints be \([L, R]\).

Retrieving \(p_2, p_3\) from history[g], the valid left endpoints are the intersection of \([L, R]\) and \([p_3+1, p_2]\).

Therefore, we compute:

  • Lower bound: \(\max(L, p_3+1)\)
  • Upper bound: \(\min(R, p_2)\)

If the lower bound is less than or equal to the upper bound, we add the number of integers in this range to the answer. If the value \(g\) has not appeared yet or has appeared fewer than \(2\) times, we add nothing.

For example, in \(A = [8, 4, 12, 4, 8]\), fixing the right endpoint at \(4\), the greatest common divisors of the subarrays with left endpoints from \(0\) to \(3\) are all \(4\).

Since the occurrence positions of the value \(4\) are \(p_1 = 3,\ p_2 = 1,\ p_3 = -1\), the valid left endpoints are the two indices \(0, 1\). The corresponding subarrays are \([8, 4, 12, 4, 8]\) and \([4, 12, 4, 8]\).

Why This Correctly Counts the Subarrays

For each right endpoint, we partition all left endpoints into groups of equal greatest common divisors. Then, from each group, we count only the left endpoints for which “the value equal to the greatest common divisor appears exactly \(2\) times.”

This is equivalent to the original condition, and since each subarray is uniquely determined by its left and right endpoints, there is neither duplicate counting nor omission.

Complexity

Let \(M = \max A_i\).

  • Time Complexity: \(O(N \log^2 M)\)
    • The number of groups maintained at each right endpoint is \(O(\log M)\).
    • This assumes that computing the greatest common divisor takes \(O(\log M)\). If the greatest common divisor computation is considered \(O(1)\), it is \(O(N \log M)\).
  • Space Complexity: \(O(N + \log M)\)
    • Uses \(O(N)\) for the input and the occurrence history dictionary, and \(O(\log M)\) for the greatest common divisor groups.

Implementation Notes

  • Update the occurrence positions to include the current element before counting.

  • Use \(-1\) for non-existent occurrence positions. When the second occurrence has not appeared yet, \(p_2 = -1\), meaning there are no valid left endpoints.

  • In implementation, one may traverse the groups from back to front, using right as the upper bound of the left-endpoint range for the current group. Note that this has a different meaning from the right endpoint \(i\) of the subarray itself.

  • The arrays can be compressed in-place by reading from the front and overwriting towards the beginning. Since the write pointer never overtakes the read pointer, unprocessed information is not lost.

  • Since \(\gcd(1, a) = 1\), if the greatest common divisor is already \(1\), the call to gcd can be omitted.

  • The answer may not fit in a \(32\)-bit integer. While this is not an issue in Python, use a \(64\)-bit integer in other languages.

    Source Code

import sys
from math import gcd


def main():
    data = list(map(int, sys.stdin.buffer.read().split()))
    n = data[0]

    gcds = []
    starts = []
    history = {}
    answer = 0

    for i in range(n):
        a = data[i + 1]

        prev = history.get(a)
        if prev is None:
            history[a] = (i, -1, -1)
        else:
            history[a] = (i, prev[0], prev[1])

        size = len(gcds)
        k = 0
        last_g = 0

        for j in range(size):
            g = gcds[j]
            if g != 1:
                g = gcd(g, a)

            if g != last_g:
                gcds[k] = g
                starts[k] = starts[j]
                k += 1
                last_g = g

        if k < size:
            del gcds[k:]
            del starts[k:]

        if last_g != a:
            gcds.append(a)
            starts.append(i)
            k += 1

        right = i
        for j in range(k - 1, -1, -1):
            left = starts[j]
            positions = history.get(gcds[j])

            if positions is not None:
                second = positions[1]
                if second >= left:
                    upper = second if second < right else right
                    lower = positions[2] + 1
                    if lower < left:
                        lower = left
                    if upper >= lower:
                        answer += upper - lower + 1

            right = left - 1

    print(answer)


if __name__ == "__main__":
    main()

This editorial was generated by gpt-6-astra-medium.

posted:
last update: