跳到正文

个人记录

[Tutorial] Square root decomposition and applications 洛谷镜像

w33z8kqrqk8zzzx33约 37 分钟
原文
文章信息与版本

文章信息

发布
2020年10月7日
收录
2025年12月12日
更新
2026年10月29日
篇幅
约 37 分钟

版本

  1. v2当前
  2. v1

A brief introduction into the applications of square root decomposition

Square root decomposition is the process of separating a structure of size O(N)O(N) into O(N)O(\sqrt{N}) “blocks” of size O(N)O(\sqrt{N}) each, in a way that aids manipulation of the entire structure. Square root decomposition is extremely versatile. Some of its most well-known use cases are:

  • answering queries on a static array, with methods such as Mo’s algorithm or block precomputation
  • “lazy” brute force modifications, where it is easy to query an entire block, but tag pushing isn’t obvious
  • separating objects based on a threshold, when there exists both an O(x)O(x) algorithm and an O(n/x)O(n/x) algorithm

In this tutorial we will walk through multiple types of square root decomposition.

Answering queries on a static array, offline (Mo’s algorithm)

Consider a problem where we are asked to find the answer for certain intervals [l,r][l,r]. We can’t quickly compute the answer for an arbitrary interval, but we know how to transition to [l,r±1][l,r\pm1] and [l±1,r][l\pm1,r] fast given some information remaining from [l,r][l,r] answer calculation. The number of transitions we need to do to get from [l1,r1][l_1,r_1] to [l2,r2][l_2,r_2] is ∣l1−l2∣+∣r1−r2∣|l_1-l_2|+|r_1-r_2|.

If there are only two intervals we need to answer such transitioning wouldn’t help us. However, if there are many intervals, choosing a good transitioning route will drastically reduce the total time needed. Finding the best transition route quick is allegedly NP-hard, so we will focus on estimating a “good enough” route.

Consider the following scheme for 2D Manhattan TSP: We do square root decomposition on the xx coordinate, separating the grid into vertical blocks, nn cells tall and BB cells wide. There are n/Bn/B such blocks.

For an arbitrary block, call the number of points we need to visit in it CC. To get to all of them, we can visit them in order from top to bottom: we spend at most O(BC)O(BC) transitions moving left and right, and O(n)O(n) transitions going down.

If for each block we need O(BC+n)O(BC+n) transitions, in total we will need O(∑(BC+n))O(\sum(BC+n)) = O(Bq+n2/B)O(Bq+n^2/B) transitions. Selecting a block size of B=O(n/q)B=O(n/\sqrt{q}) gives us a total transition count of O(qn/q+nq)O(qn/\sqrt{q}+n\sqrt{q}) = O(nq)O(n\sqrt{q}).

Implementation of sorting these transitions can be done as follows:

C++
int B = ???;
struct query {
    int l, r, id;
    const bool operator<(const query& o) const {
        if(l/B == o.l/B) {
            // they are in the same block, sort going down
            return r < o.r;
        } else {
            // they are not in the same block, sort by block number
            return l < o.l;
        }
    }
}

Observe here that between each block, we need to run from the bottom of the “grid” all the way up. We can prevent this by using a zig-zag pattern, getting a bit of a constant optimization:

C++
int B = ???;
struct query {
    int l, r, id;
    const bool operator<(const query& o) const {
        if(l/B == o.l/B) {
            if((l/B) % 2 == 0) return r < o.r;
            else return r > o.r;
        } else {
            return l < o.l;
        }
    }
}

In the following we will look at some examples.

Range distinct query (SPOJ DQUERY)

Statement: Given a static array and queries of the form [l,r][l,r], count the number of different values that occur between [l,r][l,r].

The naive transition is intuitive: we maintain a table vv where v[x]v[x] is the number of times xx occured in the interval that we are maintaining. When adding an element xx such that v[x]=0v[x]=0, increment the answer; when deleting an element xx such that v[x]=1v[x]=1, decrement the answer.

However, this needs many random accesses to this table, which is very cache-unfriendly, leading to a massive constant. Can we do better?

Consider arrays pre[i]pre[i] and nxt[i]nxt[i], which equal the last location of the element ii and the next location of the element ii, respectively (equal to some infinity if this element doesn’t exist.) We can use these arrays to quickly check whether or not some element occurs in an range.

  • Case 1: [l,r]→[l,r+1][l,r]\rightarrow[l,r+1]. We add 1 if and only if r+1r+1 has not occured in [l,r][l,r], or equivalently, pre[r+1]<lpre[r+1] < l.
  • Case 2: [l,r]→[l,r−1][l,r]\rightarrow[l,r-1]. We subtract 1 iff rr has not occured in [l,r−1][l,r-1].
  • Case 3: [l,r]→[l−1,r][l,r]\rightarrow[l-1,r]. We add 1 iff l−1l-1 has not occurned in [l,r][l,r], or equivalently, r<nxt[l−1]r < nxt[l-1].
  • Case 4: [l,r]→[l+1,r][l,r]\rightarrow[l+1,r]. We subtract 1 iff ll has not occured in [l+1,r][l+1,r].

This leads to a much quicker solution, which runs plausibly fast even for n=106n=10^6 even if we directly implement Mo’s.

Range inversion query (naive version)

Statement: Given a static array and queries of the form [l,r][l,r], count the number of pairs (i,j)(i,j) such that a[i]>a[j]a[i]>a[j]. O(nlog⁡nn)O(n\log n\sqrt n).

Every time we add or erase an element, we consider how much this element contributes to the answer. If we maintain a Fenwick tree corresponding to the current interval, we can quickly find out how many inversions involve a certain value. Transition is O(log⁡n)O(\log n); hence overall it is O(nlog⁡nn)O(n\log n\sqrt n).

Advanced: Sweepline Mo / Offline Again

This is [problem:617E], except there are multiple favorite numbers.

Statement: Given a static array, a static set SS of size CC and queries of the form [l,r][l,r], count the number of pairs (i,j)(i,j) such that a[i] xor a[j]∈Sa[i]\text{ xor }a[j]\in S. O(nC+nn)O(nC+n\sqrt n) time; O(n)O(n) memory. Assume q=O(n)q=O(n).

Notice that a[i] xor a[j]∈Sa[i]\text{ xor }a[j]\in S is equivalent to ∃v∈S:a[i] xor v=a[j]\exists v\in S:a[i]\text{ xor }v=a[j]. We can consider each vv separately and run CC instances of Mo’s, but that would be O(nCn)O(nC\sqrt n). Consider the transitions: we add an element jj and want to know the amount of ii such that a[i] xor a[j]∈Sa[i]\text{ xor }a[j]\in S and i∈[l,r]i\in[l,r].

Call the transition delta f(l,r,p)f(l,r,p) where pp is the element we are adding. Removing can be done by subtracting f(l,r−1,p)f(l,r-1,p) or f(l+1,r,p)f(l+1,r,p) depending on the direction. Sweepline Mo can be used when this transition function is differentiable: i.e. it satisfies f(l,r,p)=f(1,r,p)−f(1,l−1,p)f(l,r,p)=f(1,r,p)-f(1,l-1,p).

The main idea is to first run a “dry” Mo and find all f(1,x,p)f(1,x,p) that we need to calculate. Then, we do a sweep-line on xx, updating the data structure accordindly, and calculating the f(1,x,p)f(1,x,p) that involve this xx. We generally needs the “calculation” part to be O(1)O(1), like normal Mo, but we make more wiggle room for the update part.

However, if we store all (x,p)(x,p), we get O(nn)O(n\sqrt n) memory and a ridiculous constant factor. Notice that because of the Mo transition order, we can separate all pp into several types, given a fixed xx:

  1. p=xp=x
  2. p=x+1p=x+1
  3. p∈[A,B]p\in[A,B]

For the first and second type, we calculate ansPrev[i]ansPrev[i] and ansNext[i]ansNext[i] and don’t update anything, leaving these arrays for the second “wet” Mo to use.

For the third type, we find all (p,A,B)(p,A,B) that result from the dry Mo. There are at most 4(M−1)4(M-1) such intervals because the movement of any end of the Mo interval creates exactly one interval. Then, on the corresponding xx, we iterate through the interval and add the transition value we found to the respective query.

Example implementation:

C++
    sort(qs, qs + m);
    cl = 1, cr = 0;
    for(int i = 0; i < m; i++) {
        if (cr < qs[i].r) {
            iv[cl - 1].push_back({cr + 1, qs[i].r, i, -1});
            cr = qs[i].r;
        }
        if (qs[i].l < cl) {
            iv[cr].push_back({qs[i].l, cl - 1, i, 1});
            cl = qs[i].l;
        }
        if (qs[i].r < cr) {
            iv[cl - 1].push_back({qs[i].r + 1, cr, i, 1});
            cr = qs[i].r;
        }
        if (cl<qs[i].l) {
            iv[cr].push_back({cl, qs[i].l - 1, i, -1});
            cl = qs[i].l;
        }
    }
    for(int i = 1; i <= n; i++) {
        ansPrev[i] = ansPrev[i-1] + cgc[ar[i]];
        add(ar[i]);
        for (auto [l, r, i, c] : iv[i]) {
            ll g = 0;
            for(int p = l; p <= r; p++)
                g += cgc[ar[p]];
            ans[i] += c * g;
        }
        ansThere[i] = ansThere[i - 1] + cgc[ar[i]];
    }
    for(int i = 0; i < m; i++) {
        curans += ans[i];
        fans[qs[i].i] = curans + ansPrev[qs[i].r] + ansThere[qs[i].l-1];
    }
    for(int i = 0; i < m; i++) {
        print(fans[i]);
        pc('\n');
    }

Special implementation details:

  • Here add just updates the cgc array, which is a population count of the things in the current prefix xor the things in the set.
  • ivs is the intervals on each x, along with the query and contribution coefficient.
  • If we do a prefix sum on ansPrev and ansThere, we don’t even need to use a while loop in the second Mo.

Range inversion query, again

O(nn)O(n\sqrt n)

Consider sweepline mo. Sweepline mo in general is a method used to reduce the number of modifications of the Mo data structure to O(n)O(n), not affecting the query count of O(nn)O(n\sqrt n). This means modifications have to be at most O(n)O(\sqrt n) and queries have to be at most O(1)O(1).

For this problem we need to support point increment/decrement in O(n)O(\sqrt n) and prefix sum query in O(1)O(1). Flip it around to get an equivalent problem: suffix increment/decrement in O(n)O(\sqrt n) and point query in O(1)O(1).

Separate this auxillary array into blocks of size O(n)O(\sqrt n). For each block, maintain a value lazylazy. When we do increment/decrement a suffix, for blocks that intersect with this suffix yet are not completely covered, we change the elements with brute force. Otherwise, we modify the lazylazy tag. To query a position, we add the (brute force) value with its corresponding lazylazy tag.


For people who think there is not much of a difference between O(nn)O(n\sqrt n) and O(nlog⁡nn)O(n\log n\sqrt n): When n=100000n=100000, the former runs in 300ms300ms while the latter runs in 3000ms3000ms. Normally time limits are 1000ms1000ms.

Answering queries on a static array, online

When the data structure for Mo’s is small enough, you can use first do block decomposition into size BB and then calculate the data structure for all intervals of blocks, creating O((N/B)2)O((N/B)^2) structures.

Then, assuming the transition time for this data structure is still O(T)O(T), querying an arbitrary interval can be done in O(TB)O(TB).

Normally intialization of each structure is O(B)O(B) and transition is O(1)O(1), so it would be best to choose a block size of O(n)O(\sqrt n) to get O(nn)O(n\sqrt n) precalculation and O(n)O(\sqrt n) query time. Here we look at some examples:

[problem:522D]

Statement: Given a static array and queries of the form [l,r][l, r], for each query calculate min⁡(∣i−j∣:a[i]=a[j]∧i,j∈[l,r])\min(|i-j|:a[i]=a[j]\wedge i,j\in[l,r]). n≤500000n\le 500000

Doing Mo’s for this problem looks a bit intractable because although insertion is easy using prepre and nxtnxt arrays, it seems impossible to delete values and “roll back” the min⁡\min value. Hence we consider block decomposition, which would only require insertion.

Decompose this array into contiguous blocks of size O(B)O(B); for each contiguous interval of blocks compute the answer, for a total precomputation complexity of O((N/B)N)O((N/B)N).

Note that if we want the minimum distance the only possible jj values when we fix an ii that couuld possibly contribute to the answer are pre[i]pre[i] and nxt[i]nxt[i]. As such, when extending a precomputed block, we calculate if pre[i]pre[i] and nxt[i]nxt[i] are in the interval we need to answer, and if so we try to update the minimum, for a query complexity of O(B)O(B).

Total time complexity is O(n2/B+qB)O(n^2/B+qB), selecting B=O(n)B=O(\sqrt n) is best, getting a total time complexity of O((n+q)n)O((n+q)\sqrt n) with tiny constant. Note that input and outout for this problem is a massive portion of the total running time.

[problem:617E] online version

Statement: Given a static array, a number kk and queries of the form [l,r][l,r], for each query calculate the number of (i,j)(i,j) such that a[i] xor a[j]=ka[i]\text{ xor }a[j]=k.

a[i] xor a[j]=k  ⟺  a[i] xor k=a[j]a[i]\text{ xor }a[j]=k \iff a[i]\text{ xor }k=a[j]; we precalculate answers for each block and now count the contribution of new elements to the block interval. We want to know how many elements with value a[i] xor ka[i]\text{ xor }k there are in the current interval.

First of all the current interval is block chunk + at most O(B)O(B) elements, so we can directly maintain a population array on these O(B)O(B) elements. For the block chunk, notice that the count ”# of xx in blocks from ll to rr” is differentiable. Precalculate ”# of xx in blocks from 11 to rr”, and then we’re done.

But not quite; this method takes O(Bmax⁡A)O(B\max A) memory for the chunk count array. Notice that there are at most O(n)O(n) possible values for a[i]a[i] and a[i] xor ka[i]\text{ xor }k; hash these values and we get O(nB+(n/B)2)O(nB+(n/B)^2) memory, O((n+q)B+(n/B)2)O((n+q)B+(n/B)^2). Square root decomposition gives O((n+q)n)O((n+q)\sqrt n).

Range distinct query revisited

Statement: Range distinct query but online

Obviously direct precomputation and utilizing pre[i]pre[i] and nxt[i]nxt[i] arrays lead to an O((n+q)n)O((n+q)\sqrt n) running time. But can we do better?

Notice that the bottleneck is in the precomputation O((n/B)n)O((n/B)n), because for each block we need to compute the answers for all intervals that have this block as its first block. Yet we only store O((n/B)(n/B))O((n/B)(n/B)) values. Obviously time complexity will be lower bounded by this if we use decomposition methods. Here we will reach this lower bound.

Consider the definition of the answer for an arbitrary interval [l,r][l,r]:

A[l,r]=(∑i[pre[i]+1≤l∧i≤r])−(∑i[pre[i]+1≤l∧i≤l−1])A_{[l,r]}=(\sum_i[pre[i]+1\le l\wedge i\le r])-(\sum_i[pre[i]+1\le l\wedge i\le l-1])

Let’s put the points (pre[i]+1,i)(pre[i]+1, i) onto the 2D plane. Define a function p(x,y)p(x,y) as the number of points such that its x-coordinate is smaller than xx and its y-coordinate is smaller than yy, or a 2D prefix sum. Our answer is now

A[l,r]=p(l,r)−p(l,l−1)A_{[l,r]}=p(l,r)-p(l,l-1)

but p(x,y)p(x,y) takes O(n2)O(n^2) time to calculate. Consider transforming the AA expression to incorporate decomposition into blocks of size BB:

A[l,r]=(∑i[pre[i]/B+1≤l∧i/B≤r])−(∑i[pre[i]/B+1≤l∧i/B≤l−1])A_{[l,r]}=(\sum_i[pre[i]/B+1\le l\wedge i/B\le r])-(\sum_i[pre[i]/B+1\le l\wedge i/B\le l-1])

Now this is a prefix sum on the points (pre[i]/B+1,i/B)(pre[i]/B+1,i/B) where division is rounded down. This can obiously be computed in O((n/B)2)O((n/B)^2).

Consider the optimal choice of BB. The time complexity is

O(n2B2+qB)O(\frac{n^2}{B^2}+qB)

Selecting B=O(n3)B=O(\sqrt[3]{n}) gives us a total time complexity of

O((n+q)n3)O((n+q)\sqrt[3]{n})

This runs faster than the currently best known method of persistent segment trees because of its tiny constant for n=106n=10^6. Its memory usage is also much, much smaller.

More compilicated examples

Optimizing brute force: [problem:911G]

Statement: Given an array and operations of the form l,r,x,yl,r,x,y, set a[i]=ya[i]=y for all ii such that i∈[l,r]i\in[l,r] and a[i]=xa[i]=x. Here 1≤a[i],x,y≤1051\le a[i],x,y\le10^5.

We observe that we can apply these operations to the entire array pretty quickly by storing the locations each value occur in something simlar to a vector and do small-to-large merging.

Do block decomposition on this array into blocks of size BB. For blocks that are completely contained by an operation, do small-to-larger merging; otherwise, reconstruct this block and modify with brute force.

I don’t know how to prove the true time complexity rigorously, but we can upper bound it. If there is no brute force changes, for each block it will take a total of O(Blog⁡B)O(B\log B) time, because whenever an element is moved, the size of the vector that it is in at least doubles. Total time would thus be O(NBlog⁡B)O(NB\log B). If brute force changes on a block absolutely breaks amortized time, moving would take O((N+Q)Blog⁡B)O((N+Q)B\log B) time, for a total of O((N+Q)Blog⁡B+QN/B)O((N+Q)B\log B+QN/B). Assume Q=O(N)Q=O(N) to simplify; O(NBlog⁡B+N2/B)O(NB\log B+N^2/B). Selecting B=Nlog⁡NB=\sqrt{\frac{N}{\log N}} gives

O(NNlog⁡Nlog⁡Nlog⁡N+N2Nlog⁡N)≤O(NNlog⁡N)O(N\sqrt{\frac{N}{\log N}}\log \sqrt{\frac{N}{\log N}}+\frac{N^2}{\frac{\sqrt{N}}{\sqrt{\log N}}}) \le O(N\sqrt{N\log N})

Note here that the log⁡\log is inside the square root sign.

Value distance query

Statement: Given a static array and queries of the form x,yx, y, find min⁡(∣i−j∣:a[i]=x,a[j]=y)\min(|i-j|:a[i]=x,a[j]=y).

There are at most O(n)O(\sqrt n) values that occur more than O(n)O(\sqrt n) times. Consider a pair x,yx,y such that at least one of x,yx,y occurs more than O(n)O(\sqrt n) times. We try to precompute answers for all such x,yx, y as there are at most O(nn)O(n\sqrt n) pairs.

For all xx where xx occurs more than O(n)O(\sqrt n) times, we sweep the array using xx, once forwards and once backwards. We keep track of the last location where xx occured in the direction that we are sweeping, and then we try to update the answer for xx and a[i]a[i] (i is the index of the sweep pointer.)

As well as that, for each value keep a sorted vector of the indices where said value occurs.

When we answer queries, if we already precomputed the answer, we directly use it; otherwise, we run two-pointers on the corresponding vectors that we stored. The total time complexity is O((n+q)n)O((n+q)\sqrt n).

[Ynoi2008] rplexq

Statement: Given a rooted tree and queries of the form (l,r,x)(l,r,x), for each query find the number of i,ji,j such that l≤i<j≤rl\le i<j\le r and the LCA of ii and jj is xx.

First of all, we answer these queries offline and put the [l,r][l,r] values on the corresponding node. We do dsu on tree, maintaining an implicit segtree of the indices of nodes that belong to some subtree with small-to-large merging.

If we don’t even care about the intervals, the amount of pairs that have LCA at node xx is equal to

(szx2)−∑(szj2)\binom{sz_x}2-\sum\binom{sz_j}2

where jj is the children of xx.

When a node has a pretty small amount of children, we can answer the queries with brute force, as prefix sum queries on an implicit segtree has a small enough constant. But when a node has a lot of children AND has a lot of queries on it, this is much too slow.

First off we do a special check for the heavy child, so as to guarantee that the amount of nodes we parse are on the order of O(nlog⁡n)O(n\log n). We then take the light children and condense the indices. Now, we can run Mo’s on these indices, where what we store is ∑(colors2)\sum\binom{colors}2. Due to the ridiculously high initialization constant for Mo’s it might be better to run brute force when queries or children count is small enough.

Note that the complexity for Mo’s with length nn queries mm is O(nm)O(n\sqrt m). Because of

∑nimi≤(∑ni)max⁡m\sum n_i\sqrt m_i\le(\sum n_i)\sqrt{\max m}

the total time complexity is upper-bounded by O(nlog⁡nm)O(n\log n\sqrt m). [user:ODT,2020-10-01] claims that the time complexity can be O(nmlog⁡n)O(n\sqrt{m\log n}) to O(nm)O(n\sqrt m), but I do not know how to prove this.


If you have other interesting square root decomposition problems, please share them in the comments below and I’ll include them in the next edit!

原文
存档评论1 条抓取于