---
id: 1769
lang: en
translation_of: index.md
source_sha256: 6d0cb56b57640ec7ee7af772193d2a218d8cbc7591c38fe6517b418a0af659c2
title: "Small-to-Large Merging on Trees | DSU on tree"
description: "Small-to-large merging on trees keeps the heavy child’s data and merges the light children into it, shown on CF 600E, CF 741D and Twelve Chimes."
tags: ["OI","Brute Force","Tree Theory","Tree Problems","Small-to-Large Merging"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "树上启发式合并 / 启发式合并 rendered as “small-to-large merging (on trees)”, matching the tags.yaml rendering of 启发式合并; the English name DSU on tree in the title was kept."
  - "去个最大值 read as 取个最大值 (take the maximum), and the garbled 然后在以根节点 read as “then, at the root”."
  - "Problem name 春节十二响 translated as “Twelve Chimes of the Spring Festival”, as in the English edition of post 1092."
---

## Overview

The structure of a tree makes some data hard to merge directly and quickly, and so we have small-to-large merging on trees, a magical way of optimizing a merge that takes $O(n)$ time down to $O(\log n)$. If you have studied heavy-light decomposition before, then learning small-to-large merging on trees is very easy.

<!--more-->

## How It Works

Let’s use an example problem as an introduction: Codeforces 600E

> A tree has $n$ nodes; each node has a color, and each color has a number. For every subtree in the tree, find the sum of its “numbers of the most frequent color”. A subtree may have several “numbers of the most frequent color”, and all of them count toward the answer.

Now, this problem is easy to do in $O(n^2)$: just enumerate every node as the subtree root, then sweep once in $O(n)$. So, if we use small-to-large merging on trees instead, how do we solve this problem?

We notice that the brute-force approach does not make full use of the information inside the subtree. We consider squashing all the chains together while processing and passing them upward, so as not to waste resources.

However, we find that the tree structure cannot merge the chains perfectly. The principle of small-to-large merging is to keep the heavy child’s chain, then, with the heavy child as the base, merge the light children’s information into the heavy child and pass it upward as the situation requires.

We usually write it like this:

```cpp
// CF600E.cpp
#include <bits/stdc++.h>
#define ll long long

using namespace std;

const int MAX_N = 1e5 + 200;

int head[MAX_N], current, col[MAX_N], n, siz[MAX_N], son[MAX_N], lft[MAX_N], rig[MAX_N];
int anti[MAX_N], bucket[MAX_N], ptot;
ll most[MAX_N], answer[MAX_N];

struct edge
{
    int to, nxt;
} edges[MAX_N << 1];

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

void predfs(int u, int fa)
{
    lft[u] = ++ptot, anti[ptot] = u, siz[u] = 1;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa)
        {
            predfs(edges[i].to, u), siz[u] += siz[edges[i].to];
            son[u] = (siz[son[u]] < siz[edges[i].to]) ? edges[i].to : son[u];
        }
    rig[u] = ptot;
}

void dfs(int u, int fa, bool save)
{
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa && edges[i].to != son[u])
            dfs(edges[i].to, u, false);
    ll acc = 0;
    if (son[u] != 0)
        dfs(son[u], u, true), most[u] = most[son[u]], acc = answer[son[u]];

    if (++bucket[col[u]] > most[u])
        most[u] = bucket[col[u]], acc = col[u];
    else if (bucket[col[u]] == most[u])
        acc += col[u];

    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa && edges[i].to != son[u])
        {
            for (int id = lft[edges[i].to]; id <= rig[edges[i].to]; id++)
                if (++bucket[col[anti[id]]] > most[u])
                    most[u] = bucket[col[anti[id]]], acc = col[anti[id]];
                else if (bucket[col[anti[id]]] == most[u])
                    acc += col[anti[id]];
        }
    if (save == false)
        for (int id = lft[u]; id <= rig[u]; id++)
            --bucket[col[anti[id]]];
    answer[u] = acc;
}

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &col[i]);
    for (int i = 1, u, v; i <= n - 1; i++)
        scanf("%d%d", &u, &v), addpath(u, v), addpath(v, u);
    predfs(1, 0), dfs(1, 0, true);
    for (int i = 1; i <= n; i++)
        printf("%lld ", answer[i]);
    return 0;
}
```

For the detailed proof, see: [Small-to-Large Merging on Trees - OI Wiki](https://oi-wiki.org/graph/dsu-on-tree/)

---

Another example problem: Codeforces 741D

We notice that if the subtree contains such a chain that can be rearranged into a palindrome, then the XOR sum of its bitmask state is either zero or $2^k$ (the case with an odd count). So we first take the maximum of the answers inside the subtrees, then, at the root, use buckets to join the radii, and that’s it. See the code for details:

```cpp
// CF741D.cpp
// dsu on tree;
#include <bits/stdc++.h>

using namespace std;

const int MAX_N = 5e5 + 200;

int head[MAX_N], current, n, fa[MAX_N], siz[MAX_N], lft[MAX_N], rig[MAX_N], ptot;
int son[MAX_N], dep[MAX_N], anti[MAX_N], book[1 << 23], answer[MAX_N], dist[MAX_N];
char opt[10];

struct edge
{
    int to, nxt, weight;
} edges[MAX_N << 1];

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

void predfs(int u)
{
    lft[u] = ++ptot, siz[u] = 1, dep[u] = dep[fa[u]] + 1, anti[ptot] = u;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
    {
        dist[edges[i].to] = dist[u] ^ edges[i].weight, predfs(edges[i].to), siz[u] += siz[edges[i].to];
        if (siz[son[u]] < siz[edges[i].to])
            son[u] = edges[i].to;
    }
    rig[u] = ptot;
}

void dfs(int u, bool save)
{
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != son[u])
            dfs(edges[i].to, false), answer[u] = max(answer[u], answer[edges[i].to]);
    if (son[u] != 0)
        dfs(son[u], true), answer[u] = max(answer[u], answer[son[u]]);
    if (book[dist[u]] != 0)
        answer[u] = max(answer[u], book[dist[u]] - dep[u]);
    // iterate the mid char;
    for (int ch = 0; ch <= 21; ch++)
        if (book[dist[u] ^ (1 << ch)])
            answer[u] = max(answer[u], book[dist[u] ^ (1 << ch)] - dep[u]);
    book[dist[u]] = max(book[dist[u]], dep[u]);
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != son[u])
        {
            for (int id = lft[edges[i].to]; id <= rig[edges[i].to]; id++)
            {
                int curt = anti[id];
                if (book[dist[curt]])
                    answer[u] = max(answer[u], dep[curt] + book[dist[curt]] - (dep[u] << 1));
                // iterate the mid char;
                for (int ch = 0; ch <= 21; ch++)
                    if (book[dist[curt] ^ (1 << ch)])
                        answer[u] = max(answer[u], book[dist[curt] ^ (1 << ch)] + dep[curt] - (dep[u] << 1));
            }
            for (int id = lft[edges[i].to]; id <= rig[edges[i].to]; id++)
                book[dist[anti[id]]] = max(book[dist[anti[id]]], dep[anti[id]]);
        }
    if (save == false)
        for (int id = lft[u]; id <= rig[u]; id++)
            book[dist[anti[id]]] = 0;
}

int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d", &n);
    for (int i = 2; i <= n; i++)
        scanf("%d%s", &fa[i], opt + 1), addpath(fa[i], i, 1 << (opt[1] - 'a'));
    predfs(1), dfs(1, true);
    for (int i = 1; i <= n; i++)
        printf("%d ", answer[i]);
    return 0;
}
```

## Classic Example: [[Twelve-Province Joint Contest 2019] Twelve Chimes of the Spring Festival](https://loj.ac/problem/3052)

This problem is just a classic small-to-large-merging-on-trees <span class="slang" data-zh="裸题" data-gloss="luǒtí, “naked problem”. A problem that is a direct application of a standard algorithm.">textbook problem</span>.

```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 2e5 + 2000;
int fa[MAX_N], head[MAX_N], current, weight[MAX_N], n, size[MAX_N];
int dfn[MAX_N], tot, tmp[MAX_N];
priority_queue<int> queues[MAX_N];
struct edge
{
    int to, nxt;
} edges[MAX_N << 1];
void addpath(int src, int dst)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    head[src] = current++;
}
void dfs(int u)
{
    dfn[u] = ++tot;
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa[u])
        {
            dfs(edges[i].to);
            if (queues[dfn[edges[i].to]].size() > queues[dfn[u]].size())
                swap(dfn[edges[i].to], dfn[u]);
            int m = queues[dfn[edges[i].to]].size();
            for (int pt = 1; pt <= m; pt++)
            {
                tmp[pt] = max(queues[dfn[u]].top(),
                              queues[dfn[edges[i].to]].top());
                queues[dfn[edges[i].to]].pop();
                queues[dfn[u]].pop();
            }
            for (int pt = 1; pt <= m; pt++)
                queues[dfn[u]].push(tmp[pt]);
        }
    queues[dfn[u]].push(weight[u]);
}
int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &weight[i]);
    for (int i = 2; i <= n; i++)
        scanf("%d", &fa[i]), addpath(fa[i], i), addpath(i, fa[i]);
    dfs(1);
    long long ans = 0;
    while (!queues[dfn[1]].empty())
        ans += queues[dfn[1]].top(), queues[dfn[1]].pop();
    printf("%lld", ans);
    return 0;
}
```
