公式

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

gpt-6-astra-medium

Overview

An interval satisfies the condition if and only if “the value equal to the greatest common divisor (GCD) of the interval appears exactly \(2\) times in that interval.”

By fixing the right endpoint and grouping the left endpoints that yield the same GCD together, we can count the valid intervals without enumerating all of them.

Analysis

1. Rephrasing the condition using the greatest common divisor

Let \(m\) be the minimum value and \(g\) be the greatest common divisor of an interval.

Being able to cut all sticks into pieces of length \(m\) without remainder means that all values in the interval are multiples of \(m\). Furthermore, since the value \(m\) itself exists in the interval, the greatest common divisor of the interval must be \(m\).

Conversely, if a value equal to the GCD \(g\) exists within the interval, all values are positive multiples of \(g\), so the minimum value is also \(g\).

Therefore, the condition can be rephrased as follows:

The value equal to the GCD \(g\) of the interval appears exactly \(2\) times within the interval.

For example, the GCD of the interval \([6,12,6]\) is \(6\), and since \(6\) appears exactly \(2\) times, it satisfies the condition.

On the other hand, the GCD of the interval \([12,18]\) is also \(6\), but the value \(6\) does not appear in the interval. We need not only to find the GCD, but also to check the number of times that value appears.

2. Checking all intervals is too slow

There are \(\frac{N(N+1)}{2}\) intervals in total. Even if we update the GCD incrementally, enumerating every interval one by one requires \(O(N^2)\) operations, which will not pass within the time limit for \(N\leq 200000\).

Therefore, we fix the right endpoint and group intervals that have the same GCD together.

3. Fixing the right endpoint yields few distinct GCD values

Fix the right endpoint at \(R\), and vary the left endpoint as \(R,R-1,\ldots,1\).

As we add elements one by one to the left, the GCD changes to

\(g'=\gcd(g,A_L)\)

Since \(g'\) is a divisor of \(g\), whenever the value changes, it is guaranteed that \(g'\leq g/2\).

Thus, letting \(M=\max_i A_i\), there are only \(O(\log M)\) distinct GCD values. Moreover, the left endpoints that yield the same GCD form a contiguous range.

Therefore, instead of managing each left endpoint individually, we can maintain groups of the form:

  • The GCD \(g\)
  • The range of left endpoints \([s,t]\) that produce this GCD

4. “Exactly 2 occurrences” can be determined by the most recent positions

Let \(p_1,p_2,p_3\) be the positions where the value \(g\) appears up to the current right endpoint \(R\), in reverse chronological order (from most recent to oldest). If an occurrence does not exist, set its position to \(0\).

The condition for the interval \([L,R]\) to contain \(g\) exactly \(2\) times is:

\(p_3<L\leq p_2\)

  • If \(L\leq p_2\), it includes the two most recent occurrences.
  • If \(L>p_3\), it does not include the third or older occurrences.

Therefore, if the range of left endpoints that yield a GCD of \(g\) is \([s,t]\), the valid left endpoints that satisfy the condition are the integers in

\([s,t]\cap[p_3+1,p_2]\)

The count of such integers can be computed in constant time.

Algorithm

1. Coordinate compress the values

Create an array v of the values appearing in the array, sorted with duplicates removed.

For each value, store its last \(3\) occurrences in last. The mapping between a value and its index in v can be found using binary search.

2. Advance the right endpoint from left to right

Process the right endpoint in the order \(R=1,2,\ldots,N\). Let the value to be added be \(x=A_R\).

Update occurrence positions

Update the occurrence positions of \(x\) as follows:

  • 3rd most recent position \(\leftarrow\) 2nd most recent position
  • 2nd most recent position \(\leftarrow\) most recent position
  • Most recent position \(\leftarrow R\)

Update GCD groups

A group \((g,s,t)\) for the previous right endpoint \(R-1\) becomes

\((\gcd(g,x),s,t)\)

when extending the right endpoint to \(R\).

Update the groups in increasing order of left endpoints, and merge adjacent groups if their GCDs become identical.

In addition, append the group \((x,R,R)\) corresponding to the length-\(1\) interval \([R,R]\). Merge this with the previous group as well if they share the same GCD.

Add to the answer from each group

For each updated group \((g,s,t)\), retrieve the recent occurrence positions of the value \(g\).

If \(g\) does not appear in the original array at all, there are no valid intervals, so we ignore it.

Otherwise, let

\(\mathrm{lo}=\max(s,p_3+1)\)

\(\mathrm{hi}=\min(t,p_2)\)

and if \(\mathrm{lo}\leq\mathrm{hi}\), add

\(\mathrm{hi}-\mathrm{lo}+1\)

to the answer.

Each group partitions the intervals with right endpoint \(R\) by their GCD without overlap. Since we only count the left endpoints where the value \(g\) appears exactly \(2\) times, we can count the valid intervals without overcounting or undercounting.

Complexity

Let \(M=\max(2,\max_i A_i)\).

The number of groups maintained at each right endpoint is \(O(\log M)\). For each group, we compute the GCD and perform a binary search to look up the value.

  • Time complexity: \(O(N\log N+N\log M(\log M+\log N))\)
    • This evaluates the GCD computation using the Euclidean algorithm as \(O(\log M)\).
    • If the GCD computation is considered to take constant time, it is \(O(N\log N+N\log M\log N)\).
  • Space complexity: \(O(N+\log M)=O(N)\)

Implementation Notes

  • Use 1-based indexing for positions
    By setting non-existent occurrence positions to \(0\), cases where the value appears fewer than \(2\) times can be handled with the exact same formula. For example, if \(p_2=0\), there will be no valid left endpoints.

  • Always merge adjacent groups that have the same GCD
    If they are not merged, the number of groups will keep increasing and the optimization will fail. In the code, merging is done by extending next.back().r.

  • Use the occurrence positions up to the current right endpoint
    Update the occurrence positions of \(A_R\) before counting the intervals ending at that right endpoint.

  • Use a 64-bit integer for the answer
    Since the total number of intervals can reach \(\frac{N(N+1)}{2}\), long long is used in the code.

  • Distinguish between the group’s right boundary and the interval’s right endpoint
    l, r in Group represent the “range of positions that can be chosen as the left endpoint”. The right endpoint of the interval currently being processed is the outer loop variable r.

    Source Code

#include <bits/stdc++.h>
using namespace std;
struct Group{int g,l,r;};
int main(){
 ios::sync_with_stdio(false);cin.tie(nullptr);
 int n;cin>>n;vector<int>a(n),v;for(int &x:a)cin>>x;
 v=a;sort(v.begin(),v.end());v.erase(unique(v.begin(),v.end()),v.end());
 vector<array<int,3>> last(v.size(),{0,0,0});vector<Group> cur,next;
 long long ans=0;
 for(int r=1;r<=n;r++){
  int x=a[r-1],id=lower_bound(v.begin(),v.end(),x)-v.begin();
  auto &p=last[id];p[2]=p[1];p[1]=p[0];p[0]=r;
  next.clear();
  for(auto z:cur){z.g=gcd(z.g,x);if(!next.empty()&&next.back().g==z.g)next.back().r=z.r;else next.push_back(z);}
  if(!next.empty()&&next.back().g==x)next.back().r=r;else next.push_back({x,r,r});
  cur.swap(next);
  for(auto z:cur){
   auto it=lower_bound(v.begin(),v.end(),z.g);
   if(it==v.end()||*it!=z.g)continue;
   auto q=last[it-v.begin()];
   int lo=max(z.l,q[2]+1),hi=min(z.r,q[1]);
   if(lo<=hi)ans+=hi-lo+1;
  }
 }
 cout<<ans<<'\n';
}

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

投稿日時:
最終更新: