---
id: 1066
lang: en
translation_of: index.md
source_sha256: 22439d4b17be3ea0587e9614c9a3b99c073960af07a95bbd4b3098758c21df3f
title: "Difference on Trees"
description: "Difference on trees turns path updates into point marks around the LCA, shown on vertices (USACO Max Flow) and on edges (NOIP Transport Plan)."
tags: ["OI","Graph Theory","Tree Theory","Difference on Trees","Difference Arrays","LCA","Lowest Common Ancestor"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "Problem title “[USACO15DEC]最大流 Max Flow” already gives the English name after the Chinese one (最大流 = Max Flow); rendered once as “[USACO15DEC] Max Flow”."
  - "Chip on 坑爹玩意 (the setters’ choice of difference on trees) rendered as “this cheap trick of a thing”."
---

## A First Look at Difference on Trees

The prerequisites for learning difference on trees are:

- Lowest common ancestor (LCA)
- Linear difference arrays

Once you have learned these, we can start learning difference on trees. The idea behind difference on trees is similar to difference arrays: when we have no choice but to take prefix sums, turn range operations into single-point operations to lower the complexity. Difference on trees has appeared twice in NOIp-series contests, so it is well worth learning (I suspect the problem setters didn't dare set heavy-light decomposition, but still wanted to test how familiar contestants are with operations on trees, so they went with <span class="slang" data-zh="坑爹玩意" data-gloss="kēngdiē wányì, “a dad-cheating thing”. Internet slang for something annoying, shoddy or a letdown.">this cheap trick of a thing</span>). Let's first learn a basic operation: **vertex range add on a path**.

<!--more-->

## Vertex Range Add on a Path

First, let's grab a tree:

![graph](media/graph.png)

If we want to add one to the marks of the vertices on path $(4,7)$, how do we go about it? We can consider opening an array $tag[]$, and following the <span class="slang" data-zh="套路" data-gloss="tàolù, “routine, set pattern”. OI slang for a standard, well-known trick that works on a whole class of problems.">standard trick</span> of difference arrays, we can consider adding one at vertices $4,7$. That way, paths $(7,3),(4,7)$ both get one added. If we need to take prefix sums to get an answer, we can consider accumulating the sum directly while backtracking in $dfs$.

We will notice that the LCA of the endpoints gets counted twice during backtracking, so in difference on trees we should mark $lca$ with a $-1$, and then also give the parent of $lca$ a $-1$ mark, to make sure nothing interferes. So the whole process is very clear and simple.

Let's look at an example problem:

> [P3128](https://www.luogu.org/problemnew/show/P3128) [USACO15DEC] Max Flow
>
> FJ installed N-1 pipes between the N(2≤N≤50,000) stalls of his barn, numbered 1 to N. All the stalls are connected by the pipes.
>
> FJ has K(1≤K≤100,000) routes for transporting milk; route i carries milk from stall si to stall ti. A route puts one unit of transport pressure on the stalls at its two endpoints and on every stall it passes through in between, and you need to compute the pressure on the stall under the most pressure.

Each stall corresponds to a vertex, then for each path we can put marks using difference on trees, and finally, when tallying the answer, an $O(n)$ DFS solves it:

```cpp
// P3128.cpp
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 501000;
int head[MAX_N], n, k, current, tag[MAX_N], st[20][MAX_N], tmpx, tmpy, dep[MAX_N], ans;
struct edge
{
    int to, nxt;
} edges[MAX_N << 2];
void addpath(int src, int dst)
{
    edges[current].to = dst, edges[current].nxt = head[src];
    head[src] = current++;
}
void dfs(int u)
{
    for (int i = head[u]; i != -1; i = edges[i].nxt)
    {
        if (edges[i].to == st[0][u])
            continue;
        st[0][edges[i].to] = u, dep[edges[i].to] = dep[u] + 1;
        dfs(edges[i].to);
    }
}
int lca(int x, int y)
{
    if (dep[x] < dep[y])
        swap(x, y);
    for (int i = 19; i >= 0; i--)
        if (dep[st[i][x]] >= dep[y])
            x = st[i][x];
    if (x == y)
        return x;
    for (int i = 19; i >= 0; i--)
        if (st[i][x] != st[i][y])
            x = st[i][x], y = st[i][y];
    return st[0][x];
}
void getAns(int u)
{
    for (int i = head[u]; i != -1; i = edges[i].nxt)
    {
        if (edges[i].to == st[0][u])
            continue;
        getAns(edges[i].to), tag[u] += tag[edges[i].to];
    }
    ans = max(tag[u], ans);
}
int main()
{
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &k);
    for (int i = 1; i <= n - 1; i++)
        scanf("%d%d", &tmpx, &tmpy), addpath(tmpx, tmpy), addpath(tmpy, tmpx);
    dep[1] = 1, dfs(1);
    for (int i = 1; i < 20; i++)
        for (int u = 1; u <= n; u++)
            st[i][u] = st[i - 1][st[i - 1][u]];
    while (k--)
    {
        scanf("%d%d", &tmpx, &tmpy);
        int LCA = lca(tmpx, tmpy);
        tag[tmpx]++, tag[tmpy]++;
        tag[LCA]--, tag[st[0][LCA]]--;
    }
    getAns(1);
    printf("%d", ans);
    return 0;
}
```

## Edge Range Add on a Path

Now let's turn our attention to edges. We find that range adds on edges can actually be handled in a similar way.

Same tree as before:

![graph](media/graph.png)

If we want to add one to the weight of every edge on path $(3,7)$, how should we do it? We can consider mapping edges to vertices: a tree has $n$ vertices and $n-1$ edges, so we can let each vertex correspond to the edge from it to its parent. That way we can turn this into vertex range operations on a path.

But there are two points to note:

- Clearly, the root corresponds to no edge at all.
- In the actual operation, we will find that the edge corresponding to $lca$ does not take part in the range count on the path, so we just change the original “marks at $lca$ and at the parent of $lca$” into “mark $lca$ with $-2$”.

Example problem:

> [P2680](https://www.luogu.org/problemnew/show/P2680) Transport Plan
>
> In the year 2044 AD, humanity entered the cosmic era.
>
> Country L has $n$ planets and n-1 two-way space lanes; each lane is built between two planets, and these $n-1$ lanes connect all the planets of Country L. Little P runs a logistics company, which has many transport plans, each of the form: a logistics spaceship needs to fly from planet $u_i$ to planet $v_i$ along the fastest space route. Clearly, it takes time for a ship to travel through a lane: for lane $j$, any ship takes time $t_j$ to travel through it, and no two ships interfere with each other in any way. To encourage technological innovation, the king of Country L has agreed to let Little P's logistics company take part in building Country L's space lanes, that is, to allow Little P to convert one lane into a wormhole; ships travel through a wormhole in no time.
>
> Before the wormhole is finished, Little P's logistics company has already taken on $m$ transport plans in advance. Once the wormhole is finished, these $m$ transport plans will start at the same time, with all ships setting off together. When all $m$ transport plans are done, this phase of Little P's logistics company's work is complete.
>
> If Little P can freely choose which lane to convert into a wormhole, find the minimum time Little P's logistics company needs to complete this phase of work.

This problem is a lot more of a hassle than the previous one.

First, translating the statement: zero out the weight of one edge so that the longest of the given paths is as short as possible, and find that minimum value. We can consider binary searching the answer, searching for the length of the longest path after this operation. Then think about how to write the $check$ function: we find that for the paths whose original length is greater than the binary-search value $mid$, we can put difference-on-trees marks, then do an $O(n)$ pass counting how many times each edge is traversed: if we find the longest edge, of length $len$, that has been traversed by all the paths longer than $mid$, then we can subtract $len$ from the longest path to judge whether it exceeds $mid$. This problem is an edge range add on a path, so pay attention to how the marks are placed.

```cpp
// P2680.cpp
#include <bits/stdc++.h>
#define pr pair<int, int>
using namespace std;
const int MAX_N = 3e5 + 2000;
int n, m, head[MAX_N], current, tmpx, tmpy, tmpz, tag[MAX_N];
int fa[20][MAX_N], dist[MAX_N], dep[MAX_N], sideWeight[MAX_N];
struct edge
{
    int to, nxt, weight;
} edges[MAX_N << 1];
struct route
{
    int src, dst, dist, lca;
} routes[MAX_N];
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 dfs(int u)
{
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (fa[0][u] != edges[i].to)
        {
            dep[edges[i].to] = dep[u] + 1, fa[0][edges[i].to] = u;
            dist[edges[i].to] = dist[u] + edges[i].weight;
            sideWeight[edges[i].to] = edges[i].weight;
            dfs(edges[i].to);
        }
}
int getLCA(int x, int y)
{
    if (dep[x] < dep[y])
        swap(x, y);
    for (int i = 19; i >= 0; i--)
        if (dep[fa[i][x]] >= dep[y])
            x = fa[i][x];
    if (x == y)
        return x;
    for (int i = 19; i >= 0; i--)
        if (fa[i][x] != fa[i][y])
            x = fa[i][x], y = fa[i][y];
    return fa[0][x];
}
bool compare(route a, route b) { return a.dist > b.dist; }
void complete(int u)
{
    for (int i = head[u]; i != -1; i = edges[i].nxt)
        if (edges[i].to != fa[0][u])
            complete(edges[i].to), tag[u] += tag[edges[i].to];
}
bool check(int attempt)
{
    memset(tag, 0, sizeof(tag));
    int pubSide = 0, numOfSides = 0;
    for (int i = 1; i <= m; i++)
    {
        if (routes[i].dist <= attempt)
            break;
        tag[routes[i].src]++, tag[routes[i].dst]++;
        tag[routes[i].lca] -= 2;
        numOfSides++;
    }
    complete(1);
    for (int i = 1; i <= n; i++)
        if (tag[i] == numOfSides)
            pubSide = max(pubSide, sideWeight[i]);
    return routes[1].dist - pubSide <= attempt;
}
int main()
{
    int l = 0, r = 0;
    memset(head, -1, sizeof(head));
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n - 1; i++)
    {
        scanf("%d%d%d", &tmpx, &tmpy, &tmpz), l = max(l, tmpz);
        addpath(tmpx, tmpy, tmpz), addpath(tmpy, tmpx, tmpz);
    }
    dep[1] = 1, dfs(1);
    for (int i = 1; i < 20; i++)
        for (int j = 1; j <= n; j++)
            fa[i][j] = fa[i - 1][fa[i - 1][j]];
    for (int i = 1; i <= m; i++)
    {
        scanf("%d%d", &tmpx, &tmpy);
        route &curt = routes[i];
        curt.src = tmpx, curt.dst = tmpy, curt.lca = getLCA(tmpx, tmpy);
        curt.dist = dist[tmpx] + dist[tmpy] - 2 * dist[curt.lca];
        r = max(r, curt.dist);
    }
    sort(routes + 1, routes + 1 + m, compare);
    l = r - l;
    while (l <= r)
        if (check((l + r) >> 1))
            r = ((l + r) >> 1) - 1;
        else
            l = ((l + r) >> 1) + 1;
    printf("%d", l);
    return 0;
}
```
