公式

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

Gemini 3.8 Flash (High)

Overview

The problem asks us to find the total number of contiguous subarrays \([L, R]\) such that the greatest common divisor (GCD) of the subarray equals the minimum value \(m\) in that subarray, and this value \(m\) appears exactly \(2\) times within the subarray.

By utilizing the property that, for a fixed right endpoint \(R\), the number of distinct values of the cumulative GCD is at most \(O(\log(\max A))\) (the property of GCD intervals), we can solve this problem efficiently in \(O(N \log^2(\max A))\).


Analysis

1. Rephrasing the Conditions

Let us break down the two conditions of the problem: - Condition 2: Every element in the subarray is divisible by \(m\). Letting \(g = \gcd(A_L, A_{L+1}, \dots, A_R)\) be the GCD of the entire subarray, this means that \(g\) is a multiple of \(m\) (\(g \ge m\)). - Condition 1: A stick of length \(m\) exists in the interval. Since \(m\) is one of the elements in the interval, by the definition of the greatest common divisor, \(g\) must be a divisor of \(m\) (\(g \le m\)).

From the above, \(g = m\) must always hold. Furthermore, if a positive integer \(g\) is an element of the interval and a divisor of all elements in the interval, \(g\) is automatically the minimum value of that interval.

Therefore, the condition of the problem can be simply rephrased as follows:

“The greatest common divisor of the interval \(g = \gcd(A_L, \dots, A_R)\) appears exactly \(2\) times in the interval \(A[L..R]\).”

2. Naive Approach and Its Limitations

There are \(O(N^2)\) pairs of intervals \((L, R)\). Checking the GCD and counting elements for each interval would take \(O(N^3)\) or \(O(N^2 \log(\max A))\) in the worst case, which will exceed the time limit (TLE) for \(N \le 200000\).

3. Key Properties of GCD

Consider fixing the right endpoint \(R\) and extending the left endpoint \(L\) to the left from \(R\) towards \(1\). As the interval expands, the cumulative GCD \(\gcd(A_L, \dots, A_R)\) is monotonically non-increasing (decreases or stays the same).

Whenever the GCD changes, the new value must be a divisor of the previous one, so it becomes at least \(\frac{1}{2}\) or less. Since the maximum value is \(10^9\), the GCD can change at most \(\log_2(10^9) \approx 30\) times. In other words, for a fixed \(R\), there are at most around 30 possible GCD values, and the values of \(L\) yielding the same GCD form contiguous intervals.

4. Fast Counting of Valid \(L\)

While iterating over \(R\), we maintain intervals \([l, r]\) grouped by their GCD (i.e., the range of \(L\) such that \(\gcd(A_L, \dots, A_R) = g\) for \(L \in [l, r]\)).

Now, consider the condition on \(L\) such that \(g\) appears exactly \(2\) times in the interval \([L, R]\). Let \(q_1, q_2, q_3\) be the positions of occurrences of the value \(g\) that are \(\le R\), listed from right to left (\(q_1\) is the rightmost, \(q_2\) is the second, and \(q_3\) is the third): - \(g\) is contained at least \(2\) times in the interval \(\implies L \le q_2\) - \(g\) is not contained \(3\) or more times in the interval \(\implies L > q_3\) (\(q_3 + 1 \le L\))

Therefore, the condition that \(L\) must satisfy is \(q_3 + 1 \le L \le q_2\) (if \(q_3\) does not exist, \(0 \le L \le q_2\)).

Thus, for each GCD interval \([l, r]\), we only need to add the length of its intersection with the valid range \([q_3 + 1, q_2]\): $\( \max(0, \min(r, q_2) - \max(l, q_3 + 1) + 1) \)$ to the answer.


Algorithm

  1. Prepare an associative array (hash map) pos to record the last \(3\) positions of occurrence for each value.
  2. Iterate over the right endpoint \(i\) from \(0\) to \(N-1\):
    • Update pos[A[i]] to record the latest \(3\) occurrences \((q_1, q_2, q_3)\).
    • For each element \((g, l, r)\) in the list of GCD intervals from the previous step, compute \(\gcd(g, A_i)\) to create a new list of intervals. During this process, merge adjacent intervals that have the same GCD value.
    • Append (or merge) the single-element interval \((A_i, i, i)\) for the new element \(A_i\) to the end.
    • For each resulting GCD interval \((g, l, r)\):
      • Retrieve the occurrence history of the value \(g\) from pos.
      • If \(g\) has appeared \(2\) or more times, compute the width of the overlapping range \([\max(l, q_3 + 1), \min(r, q_2)]\) and add it to the answer.
  3. Output the final total count.

Complexity

  • Time Complexity: \(O(N \log^2(\max A))\)
    • For each \(i\), the number of maintained GCD intervals is at most \(\log_2(\max A)\).
    • When generating the next set of intervals from the previous ones, a GCD computation (taking \(O(\log(\max A))\) time) is performed for each interval.
    • Therefore, the time complexity per step is \(O(\log^2(\max A))\), leading to an overall time complexity of \(O(N \log^2(\max A))\).
    • Since \(\log_2(10^9) \approx 30\), this runs well within the time limit.
  • Space Complexity: \(O(N)\)
    • The hash map pos stores at most \(N\) distinct entries.
    • The size of the GCD interval list is always \(O(\log(\max A))\).

Implementation Notes

  • Compressing GCDs like Run-Length Encoding: When constructing the new list of GCDs, if an interval has the same GCD value as the previous one, extend the right endpoint of that interval to merge them. This keeps the list length at most around 30 at all times.

  • Using Sentinels: To reduce case distinctions when the number of occurrences is fewer than \(2\) or fewer than \(3\), treating non-existent indices as \(-1\) simplifies the implementation. When \(q_3 = -1\), \(q_3 + 1 = 0\), which naturally handles the case of having “no lower bound”.

  • Safely Computing the Intersection Length: After finding \(\text{low} = \max(l, q_3 + 1)\) and \(\text{high} = \min(r, q_2)\), adding \(\text{high} - \text{low} + 1\) only when \(\text{low} \le \text{high}\) prevents incorrect additions when there is no intersection (which would yield a negative value).

    Source Code

import sys
import math

def main():
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    n = int(input_data[0])
    a = [int(x) for x in input_data[1:n+1]]
    
    gcd = math.gcd
    pos = {}
    prev_gcds = []
    ans = 0
    
    for i in range(n):
        x = a[i]
        
        p = pos.get(x)
        if p is None:
            pos[x] = (i, -1, -1)
        else:
            pos[x] = (i, p[0], p[1])
            
        new_gcds = []
        for g, l, r in prev_gcds:
            ng = gcd(g, x)
            if new_gcds and new_gcds[-1][0] == ng:
                new_gcds[-1] = (ng, new_gcds[-1][1], r)
            else:
                new_gcds.append((ng, l, r))
                
        if new_gcds and new_gcds[-1][0] == x:
            new_gcds[-1] = (x, new_gcds[-1][1], i)
        else:
            new_gcds.append((x, i, i))
            
        for g, l, r in new_gcds:
            p = pos.get(g)
            if p is not None and p[1] != -1:
                q2 = p[1]
                q3 = p[2]
                low = l if l > q3 + 1 else q3 + 1
                high = r if r < q2 else q2
                if low <= high:
                    ans += high - low + 1
                    
        prev_gcds = new_gcds
        
    print(ans)

if __name__ == '__main__':
    main()

This editorial was generated by gemini-3.8-flash-high.

投稿日時:
最終更新: