Olympiad in Informatics

Kruskal Reconstruction Tree

Overview

The Kruskal reconstruction tree is a kind of spanning tree of a graph, mainly used to solve a class of problems with restrictions on the edge weights along paths. The Kruskal reconstruction tree has the property of being monotonic in depth, so it can easily handle restrictions on the range of edge weights.

Construction

The Kruskal reconstruction tree is built in a way very similar to how Kruskal's algorithm builds a minimum spanning tree, but the structure is different: the Kruskal reconstruction tree turns edge weights into node weights, and the node weights get smaller with depth. Suppose we have a graph like this:

graph

When building the reconstruction tree, we remove all the edges:

graph (1)

Then we iterate over the edges in order of weight from smallest to largest. After finding the shortest edge we do a DSU query; if the two points are not in the same connected component, we create a new node whose node weight is this edge's weight, and then this new node connects the two points and becomes the representative element of the whole big connected component:

graph (3)

The nodes with parentheses are the nodes newly added in the reconstruction tree, and inside the parentheses are their weights. We find that as the depth decreases, the weights increase monotonically (not strictly). This property lets us satisfy the problem's restrictions on edge weights.

Example A: P4197 Peaks

In Bytemountains there are \(N\) peaks, and each peak has its height \(h_i\). Some peaks are connected by two-way roads, \(M\) paths in total, and each path has a difficulty value; the larger this value, the harder the path is to walk. Now there are \(Q\) queries. Each query asks, starting from point \(v\) and using only paths whose difficulty is at most \(x\), for the \(k\)-th highest peak among the peaks that can be reached. If there is no solution, output \(-1\).

This problem puts a restriction on the path: the weights of all edges on the path are less than \(x\). We can find on the Kruskal spanning tree the first node whose node weight is less than \(x\), and then we find that the points in its subtree all satisfy this condition. We can do a \(DFS\) order, and then a value-indexed persistent segment tree takes care of the \(k\)-th largest problem.

// P4197.cpp
#include <bits/stdc++.h>
using namespace std;

const int MAX_N = 2e5 + 5, MAX_M = 5e5 + 5, MAX_T = 20 * MAX_N;

int head[MAX_N], current, fa[20][MAX_N], tot, n, m, q, hi[MAX_N], tmpx, tmpy, tmpz;
int buff[MAX_N], tmp[MAX_N], limit, pval[MAX_N], lft[MAX_N], rig[MAX_N], dfn;
int sum[MAX_T], lson[MAX_T], rson[MAX_T], roots[MAX_N], ttot;
struct edge
{
    int from, to, weight, nxt;
    bool operator<(const edge &e) const { return weight < e.weight; }
} G[MAX_M], edges[MAX_N];

void addpath(int src, int dst, int weight)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    edges[current].from = src, edges[current].weight = weight;
    head[src] = current++;
}

int find(int x) { return (buff[x] == x) ? x : buff[x] = find(buff[x]); }

int update(int qx, int l, int r, int pre)
{
    int p = ++ttot;
    sum[p] = sum[pre] + 1;
    if (l == r)
        return p;
    int mid = (l + r) >> 1;
    rson[p] = rson[pre], lson[p] = lson[pre];
    if (qx <= mid)
        lson[p] = update(qx, l, mid, lson[pre]);
    else
        rson[p] = update(qx, mid + 1, r, rson[pre]);
    return p;
}

int query(int a, int x, int k)
{
    int l = 1, r = limit;
    for (int i = 19; i >= 0; i--)
        if (fa[i][a] != 0 && pval[fa[i][a]] <= x)
            a = fa[i][a];
    int v = roots[rig[a]], u = roots[lft[a] - 1];
    if (sum[v] - sum[u] < k)
        return -1;
    while (l < r)
    {
        int tp = sum[rson[v]] - sum[rson[u]], mid = (l + r) >> 1;
        if (tp >= k)
            v = rson[v], u = rson[u], l = mid + 1;
        else
            v = lson[v], u = lson[u], r = mid, k -= tp;
    }
    return tmp[r];
}

void dfs(int u)
{
    for (int i = 1; i < 20; i++)
        fa[i][u] = fa[i - 1][fa[i - 1][u]];
    lft[u] = ++tot;
    if (u <= n)
        roots[tot] = update(hi[u], 1, limit, roots[tot - 1]);
    else
        roots[tot] = roots[tot - 1];
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        dfs(edges[i].to);
    rig[u] = tot;
}

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d%d", &n, &m, &q);

    for (int i = 1; i <= 2 * n; i++)
        buff[i] = i;

    for (int i = 1; i <= n; i++)
        scanf("%d", &hi[i]), tmp[i] = hi[i];
    for (int i = 1; i <= m; i++)
        scanf("%d%d%d", &tmpx, &tmpy, &tmpz), G[i] = edge{tmpx, tmpy, tmpz, -1};

    sort(tmp + 1, tmp + 1 + n), limit = unique(tmp + 1, tmp + 1 + n) - tmp - 1;
    for (int i = 1; i <= n; i++)
        hi[i] = lower_bound(tmp + 1, tmp + 1 + limit, hi[i]) - tmp;

    dfn = n, sort(G + 1, G + 1 + m);

    for (int i = 1; i <= m; i++)
    {
        int a = find(G[i].from), b = find(G[i].to);
        if (a != b)
        {
            pval[++dfn] = G[i].weight, buff[a] = buff[b] = dfn;
            addpath(dfn, a, 0), addpath(dfn, b, 0);
            fa[0][a] = fa[0][b] = dfn;
            if (dfn - n == n - 1)
                break;
        }
    }

    for (int i = 1; i <= dfn; i++)
        if (lft[i] == 0)
            dfs(find(i));

    while (q--)
    {
        int v, x, k;
        scanf("%d%d%d", &v, &x, &k), printf("%d\n", query(v, x, k));
    }
    return 0;
}

Example B: P4768 [NOI2018] Return Journey

This is actually yet another Kruskal reconstruction tree stupid-easy problem. We consider first running a shortest path on each graph (note that this problem kills SPFA), then building a Kruskal reconstruction tree (sorting by altitude from high to low). Consider using binary lifting to find the point whose node weight is closest to the query, then just look in its subtree for the point with the shortest shortest-path distance. The point with the shortest distance can be handled in advance with one DFS. The time complexity of the whole preprocessing is \(O(n \log n)\), and the overall complexity is \(O(T * n \log n)\).

// P4768.cpp
#include <bits/stdc++.h>
#define pr pair<int, int>
using namespace std;

const int MAX_N = 4e5 + 2000, MAX_M = 4e5 + 2000, INF = 0x3f3f3f3f;

int T, n, m;
int head_graph[MAX_N], head_tree[MAX_N], current_graph, current_tree, buff[MAX_N];
int ptot, fa[20][MAX_N], val[MAX_N], smallest[MAX_N], dist[MAX_N];
bool vis[MAX_N];

struct edge
{
    int from, to, nxt, weight, height;
    bool operator<(const edge &e) const { return height > e.height; }
} source[MAX_M], edges[MAX_M << 1], tree[MAX_N];

int find(int x) { return x == buff[x] ? x : buff[x] = find(buff[x]); }

void addpath(int src, int dst, int weight, int height)
{
    edges[current_graph].to = dst, edges[current_graph].height = height;
    edges[current_graph].nxt = head_graph[src], edges[current_graph].weight = weight;
    head_graph[src] = current_graph++;
}

void addbranch(int src, int dst)
{
    tree[current_tree].to = dst, tree[current_tree].nxt = head_tree[src];
    head_tree[src] = current_tree++;
}

void djisktra()
{
    memset(dist, 0x3f, sizeof(dist)), memset(vis, false, sizeof(vis));
    priority_queue<pr> pq;
    pq.push(make_pair(0, 1)), dist[1] = 0;
    while (!pq.empty())
    {
        int u = pq.top().second;
        pq.pop();
        if (vis[u])
            continue;
        vis[u] = true;
        for (int i = head_graph[u]; i != -1; i = edges[i].nxt)
            if (!vis[edges[i].to] && dist[edges[i].to] > dist[u] + edges[i].weight)
                dist[edges[i].to] = dist[u] + edges[i].weight, pq.push(make_pair(-dist[edges[i].to], edges[i].to));
    }
}

void dfs(int u)
{
    smallest[u] = 0;
    if (u <= n)
        smallest[u] = u;
    for (int i = 1; i < 20; i++)
        fa[i][u] = fa[i - 1][fa[i - 1][u]];
    for (int i = head_tree[u]; i != -1; i = tree[i].nxt)
    {
        fa[0][tree[i].to] = u, dfs(tree[i].to);
        if (dist[smallest[u]] > dist[smallest[tree[i].to]])
            smallest[u] = smallest[tree[i].to];
    }
}

void kruskal()
{
    sort(source + 1, source + 1 + m);
    for (int i = 1; i <= m; i++)
    {
        int a = find(source[i].from), b = find(source[i].to);
        if (a != b)
        {
            int p = ++ptot;
            buff[a] = buff[b] = buff[p] = p, val[p] = source[i].height;
            fa[0][a] = fa[0][b] = p;
            addbranch(p, a), addbranch(p, b);
        }
    }
    dist[0] = INF, dfs(ptot);
}

int find_smallest(int u, int limit)
{
    for (int i = 19; i >= 0; i--)
        if (fa[i][u] && val[fa[i][u]] > limit)
            u = fa[i][u];
    return u;
}

int main()
{
    scanf("%d", &T);
    while (T--)
    {
        scanf("%d%d", &n, &m);
        memset(head_graph, -1, sizeof(head_graph)), memset(head_tree, -1, sizeof(head_tree));
        current_graph = current_tree = 0, ptot = n;
        memset(fa, 0, sizeof(fa)), memset(val, 0, sizeof(val)), memset(smallest, 0, sizeof(smallest));
        for (int i = 1; i <= 2 * n; i++)
            buff[i] = i;
        for (int i = 1; i <= m; i++)
        {
            scanf("%d%d%d%d", &source[i].from, &source[i].to, &source[i].weight, &source[i].height);
            addpath(source[i].from, source[i].to, source[i].weight, source[i].height);
            addpath(source[i].to, source[i].from, source[i].weight, source[i].height);
        }
        djisktra(), kruskal();
        int lastans = 0, q, k, s;
        scanf("%d%d%d", &q, &k, &s);
        while (q--)
        {
            int v, p;
            scanf("%d%d", &v, &p), v = (v + k * lastans - 1) % n + 1, p = (p + k * lastans) % (s + 1);
            int ans = find_smallest(v, p);
            printf("%d\n", lastans = dist[smallest[ans]]);
        }
    }
    return 0;
}