NeFut Logo NeFut
Admin Login

Re-rooting Technique and Global Path Optimization in Tree Dynamic Programming

Published at: 2026-05-27 09:17 Last updated: 2026-06-06 13:04
#C++ #Tutorial

Core Logic and Mathematical Principles

In the advanced form of Tree Dynamic Programming (Tree DP), the Re-rooting technique (Re-rooting / Up-and-Down Tree DP) is specifically designed to solve the "Global Tree Path Topology Problem".

In standard Tree DP, we typically assume a fixed node (such as node $1$) as the root. In this case, the state can only backtrack contributions along the topology axis from bottom to top (from child nodes to parent nodes). If the problem requires calculating the global statistics for each node in the tree as its own root (e.g., the sum of distances from all nodes to node $i$ when node $i$ is the root), running a DFS of $O(N)$ for each node would result in a disastrous complexity of $O(N^2)$.

The Re-rooting technique allows us to utilize two scans to map the global state without loss in linear time $O(N$) by leveraging the topological shifts of local states.

1. First Scan: Bottom-to-Up

$$size[u] = 1 + \sum_{v \in \text{son}(u)} size[v]$$

$$f[u] = \sum_{v \in \text{son}(u)} (f[v] + size[v])$$

2. Second Scan: Up-to-Down (Re-rooting Evolution)

$$g[v] = g[u] - size[v] + (N - size[v]) = g[u] + N - 2 \cdot size[v]$$

With this $O(1)$ algebraic differential equation, we can directly compute the true statistics when child node $v$ is the global root during the second DFS progressing from top to bottom along the edges.


State Design and Algorithm Derivation

1. State Space Definition

2. Topological Propagation Control Matrix


C++ Standard Source Code (NOIP Style)

The following source code solves the classic global tree path sum problem: "Find which node in the tree minimizes the sum of distances from all nodes to it when it is the root, and output that minimum value," strictly compatible with Linux g++ -O2 compilation standards.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

const int MAXN = 200005;

int n;
vect...  // Omitted intermediate parts

    cout << min_dist << "\n";

    return 0;
}

NOIP Practical Pitfall Guide

1. Pre-order and Post-order Position Reversal in the Second Scan

This will cause the current branch to use the initial unassigned 0 or dirty data for child node $v$ and all its descendants during the downward recursion. The global state grid will collapse completely when the recursion returns.

2. Re-rooting Multiplication Overflow and Incorrect Constant Coefficient Signs


Classic NOIP/Luogu Real Problems

1. Luogu P3478 [STA-Station]

2. Luogu P2986 [USACO10MAR] Great Cow Gathering G

$$g[v] = g[u] - size[v] \cdot W + (\text{TotalCow} - size[v]) \cdot W$$

By elevating simple node counting to weight counting, this perfectly solves the rapid localization of the centroid in weighted trees.

Original Source: local://16.3

[h] Back to Home