Olympiad in Informatics

Divide and Conquer & Sqrt Decomposition Study Notes

Divide and Conquer

Tree Divide and Conquer - Centroid Decomposition

First pick a vertex as the root, turning the unrooted tree into a rooted one, then recursively branch out (DFS-like). But to cut down the complexity, we want to keep the recursion depth in a tree as small as possible, so the choice of this vertex matters a lot. We pick the centroid to take care of this. With the centroid, none of our subtrees has size above \(n/2\); once the computation is done, delete the root and recurse into the subtrees. So the time complexity is a nice \(O(n\log n)\).

How to find the centroid: we spend \(O(n)\) time computing the size of the subtree rooted at each vertex, then find the vertex that splits off connected components with the fewest vertices; that vertex is the centroid.

Examples: IOI2011 Race, POJ1741: Tree — Solution

Idea: find the centroid; then a path can be expressed as two sub-paths through the root. In the first DFS, record the distance and the number of edges to reach each vertex, and at the same time keep track of the minimum number of edges to reach distance \(dist\), \(sides[dist]\). The answer is

\[ans=max\{sides[k-dist[i]]+sideSubtree[i]\}\]

Make sure to finish counting the answer before you use \(sideSubtree\) to update the \(sides[]\) array.

Tree Divide and Conquer - Edge Centroid Decomposition

You still need to find the centroid, but in some extreme cases (star graphs and the like) things go wrong and the complexity shoots up. At that point you can rig up a rebuilt tree to fix it, turning a star graph into a binary tree (add virtual vertices, add zero-weight edges) (I don't really get it yet)

For details, see this article: https://ksmeow.moe/edge_based_divide_and_conquer/

Example: BZOJ2870

Tree Divide and Conquer - Heavy-Light Decomposition

Heavy-light decomposition is a handy thing. In the first DFS we can find all the heavy children, and in the second DFS we visit the heavy child first and compute the timestamps.

For range operations on a heavy chain, just brute-force them as range operations over the timestamps; for light edges or mixed chains, an LCA-like algorithm can handle it.

There are tons of problems on this on Luogu, so I won't give examples.

CDQ Divide and Conquer

CDQ divide and conquer is a godlike offline algorithm. The teacher went too fast and switched away from the slides before I finished reading them.

Parallel Binary Search

What it does: binary-search over all the queries to speed things up.

Sqrt Decomposition

Plain Sqrt Decomposition

The most important thing in plain sqrt decomposition is choosing the interval length. Choosing a good interval length can bring the time complexity way down. Usually we use \(\sqrt{n}\) as the interval length. Store the left and right endpoints and the block each position belongs to in arrays, and precompute the necessary information.

Example: Contest Hunter 4401 - Dandelion

This problem asks us to maintain the mode. We can first precompute the mode between every two blocks, then give each number a \(vector\) recording the positions where it appears; for the brute-force parts of the range, we can binary search twice and subtract to get the number of occurrences. That solves the problem:

// CH4401.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 40100;
vector<int> poses[MAX_N];
int arr[MAX_N], mapping[MAX_N], lft[MAX_N], tot, rig[MAX_N], cnt[MAX_N], mode[900][900], affiliate[MAX_N];
int find(int x, int l, int r)
{
    return upper_bound(poses[x].begin(), poses[x].end(), r) - lower_bound(poses[x].begin(), poses[x].end(), l);
}
void judge(int x, int l, int r, int &ans, int &ct)
{
    int w = find(x, l, r);
    if (w > ct || (w == ct && x < ans))
        ct = w, ans = x;
}
int query(int l, int r)
{
    int ans = 0, ct = 0;
    int p = affiliate[l], q = affiliate[r];
    if (p == q)
    {
        for (int i = l; i <= r; i++)
            judge(arr[i], l, r, ans, ct);
        return mapping[ans];
    }
    int x = 0, y = 0;
    if (p + 1 <= q - 1)
        x = p + 1, y = q - 1;
    for (int i = l; i <= rig[p]; i++)
        judge(arr[i], l, r, ans, ct);
    for (int i = lft[q]; i <= r; i++)
        judge(arr[i], l, r, ans, ct);
    if (mode[x][y])
        judge(mode[x][y], l, r, ans, ct);
    return mapping[ans];
}
int main()
{
    int n, m, t, len;
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; i++)
        scanf("%d", &arr[i]), mapping[++tot] = arr[i];
    sort(mapping + 1, mapping + 1 + n);
    tot = unique(mapping + 1, mapping + 1 + n) - (mapping + 1);
    for (int i = 1; i <= n; i++)
        arr[i] = lower_bound(mapping + 1, mapping + 1 + tot, arr[i]) - mapping, poses[arr[i]].push_back(i);
    t = sqrt(log(n) / log(2) * n);
    len = t ? n / t : n;
    for (int i = 1; i <= t; i++)
        lft[i] = (i - 1) * len + 1, rig[i] = i * len;
    if (rig[t] < n)
        lft[t + 1] = rig[t] + 1, rig[++t] = n;
    for (int i = 1; i <= t; i++)
        for (int j = lft[i]; j <= rig[i]; j++)
            affiliate[j] = i;
    memset(mode, 0, sizeof(mode));
    for (int i = 1; i <= t; i++)
    {
        memset(cnt, 0, sizeof(cnt));
        int ct = 0, ans = 0;
        for (int j = lft[i]; j <= n; j++)
        {
            if (++cnt[arr[j]] > ct || (cnt[arr[j]] == ct && arr[j] < ans))
                ans = arr[j], ct = cnt[arr[j]];
            mode[i][affiliate[j]] = ans;
        }
    }
    int last = 0;
    while (m--)
    {
        int l, r;
        scanf("%d%d", &l, &r), l = (l + last - 1) % n + 1, r = (r + last - 1) % n + 1;
        if (l > r)
            swap(l, r);
        last = query(l, r);
        printf("%d\n", last);
    }
    return 0;
}

Mo's Algorithm

For problems that can be done offline, we consider splitting the queries into blocks. First brute-force the first query in each block, then every other query in the block takes \(O(\sqrt{n})\) time to handle the transition. Very handy.

Example: BZOJ2038: [2009 National Training Team] Little Z's Socks (hose)

Clearly, the formula for the answer of a range, computed on its own, is:

\[\frac{ans}{ {r-l+1 \choose 2}}, \text{where ans is the number of pairs of matching socks.}\]

For each block, we can maintain a \(num[]\) array recording how many times each color appears, then accumulate ans during the transitions and update the query answers, and that's it.

// BZ2038.cpp
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const ll MAX_N = 50100;
struct query
{
    ll l, r, id, answerSon, answerDom;
    bool operator<(const query &qy) const { return id < qy.id; }
} queries[MAX_N];

ll ci[MAX_N], n, m, len, btot, num[MAX_N], lft[MAX_N], rig[MAX_N], ans;

bool compare_left(query a, query b) { return a.l < b.l || (a.l == b.l && a.r < b.r); }
bool compare_right(query a, query b) { return a.r < b.r || (a.r == b.r && a.l < b.l); }
ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); }

void change(ll x, ll w)
{
    ans -= num[x] * (num[x] - 1);
    num[x] += w;
    ans += num[x] * (num[x] - 1);
}

void simplify(ll id)
{
    ll d = gcd(queries[id].answerSon, queries[id].answerDom);
    if (!d)
        queries[id].answerSon = 0, queries[id].answerDom = 1;
    else
        queries[id].answerSon /= d, queries[id].answerDom /= d;
}

int main()
{
    scanf("%lld%lld", &n, &m);
    for (ll i = 1; i <= n; i++)
        scanf("%lld", &ci[i]);
    for (ll i = 1; i <= m; i++)
        scanf("%lld%lld", &queries[i].l, &queries[i].r), queries[i].id = i;

    len = sqrt(m), btot = m / len;
    sort(queries + 1, queries + 1 + m, compare_left);
    for (ll i = 1; i <= btot; i++)
        lft[i] = (i - 1) * len + 1, rig[i] = i * len;
    if (rig[btot] < m)
        lft[btot + 1] = rig[btot++] + 1, rig[btot] = m;

    for (ll i = 1; i <= btot; i++)
    {
        sort(queries + lft[i], queries + rig[i] + 1, compare_right);
        memset(num, 0, sizeof(num));
        ans = 0;
        // previous interval;
        ll l = queries[lft[i]].l, r = queries[lft[i]].r;
        // process the first query;
        for (ll j = l; j <= r; j++)
            change(ci[j], 1);
        queries[lft[i]].answerSon = ans;
        queries[lft[i]].answerDom = (queries[lft[i]].r - queries[lft[i]].l + 1) * (queries[lft[i]].r - queries[lft[i]].l);
        simplify(lft[i]);

        for (ll j = lft[i] + 1; j <= rig[i]; j++)
        {
            while (l < queries[j].l)
                change(ci[l++], -1);
            while (l > queries[j].l)
                change(ci[--l], 1);
            while (r < queries[j].r)
                change(ci[++r], 1);
            while (r > queries[j].r)
                change(ci[r--], -1);
            if (queries[j].l == queries[j].r)
                queries[j].answerSon = 0, queries[j].answerDom = 1;
            else
            {
                queries[j].answerSon = ans, queries[j].answerDom = (r - l) * (r - l + 1);
                simplify(j);
            }
        }
    }

    sort(queries + 1, queries + 1 + m);
    for (ll i = 1; i <= m; i++)
        printf("%lld/%lld\n", queries[i].answerSon, queries[i].answerDom);
    return 0;
}

Mo's Algorithm on Trees

Convert the tree problem into a sequence problem; the bracket sequence (Euler tour order) solves it. Example: SPOJ COT 2