Skip to the workspace
Pebellslearn by building
Planning DP  ›  Lesson

DP on Trees & the Night Depots

DP on Trees 34 minSolve each branch once, bottom-up, and hand the parent one answer per state

dsa / DP on Trees & the Night Depots

Explore each scene at your own pace.

01 · One number isn't enough

One number isn't enough

DP on Trees & the Night Depots

Definition
Tree dynamic programming solves a problem on a tree by computing each node's answer from its children's answers, working from the leaves up to the root, and storing one result per state the parent needs to know about.
In plain words
Think of a company chart where each manager reports a summary upward. A manager waits for every team below to report, combines those summaries, and passes one up, and the summary covers both 'I take part' and 'I sit out'.

In short: a tree DP solves leaves first and works up to the root, because a node's answer only depends on its children, and no two children's branches overlap. One number per node often isn't enough, since the parent may care about something the child can't see from a single best score — so each node returns one answer per state the parent cares about (here, a pair: the best demand if this depot is open, and if it's closed). The parent combines its children's pairs and hands its own pair further up.

Six depots as a tree, each badged t=take s=skip after a post-order sweep: leaves 1/0, North 6/2, South 5/1, Hub 10/11, with Hub's closed branch (11) circled as the winner

Meridian's depots form a tree. The central hub supplies district depots, which supply local ones, and every depot has exactly one parent it gets its stock from. At night only some depots stay open. Two depots joined by a direct road share one night security patrol, so a depot and its parent can't both be open. Every depot has a different overnight demand. Which depots should open?

This is the grid problem again in a different shape. On a grid, a cell's answer came from the cells above and to the left. On a tree, a depot's answer comes from its children, and each child's answer is about its own branch, which no other branch overlaps. Solve the leaves first and work up to the root, and every branch is solved exactly once.

One number isn't enough

Try "the best demand in this depot's branch". Then the hub asks its child North: what's the best you can do? North says 6, but that 6 comes from North being open, and an open hub isn't allowed to use it. The child has to answer two questions, one for each thing the parent might do:

  • take: the best demand in my branch if I'm open. Then all my children must be closed: demand + Σ child.skip.
  • skip: the best demand in my branch if I'm closed. Then each child does whatever is better for it: Σ max(child.take, child.skip).

The answer for the whole city is max(root.take, root.skip). Here it is on six depots, with each depot badged t=take s=skip as the post-order sweep reaches it:

watch it move · tree

Post-order fills every child's pair before its parent's, and the parent combines them. Demands are Hub 7, North 6, South 5, and 1 at each leaf.

Dock is a leaf. Open, it serves its demand of 1. Closed, it serves 0. Binary tree, 6 nodes, height 3. At node Dock.

1 / 8

The pair is what makes this work. Each child hands up one answer per state the parent cares about, and the parent never has to look further down than its own children.

python

The code handles any number of children, since the loop doesn't care. The pictures in this lesson use at most two per depot only so they fit on screen.

Predict a small one before you run anything:

What does this print?
def solve(node):
    take, skip = node["demand"], 0
    for child in node["children"]:
        t, s = solve(child)
        take += s
        skip += max(t, s)
    return take, skip

chain = {"demand": 4, "children": [{"demand": 5, "children": [{"demand": 4, "children": []}]}]}
print(max(solve(chain)))

And one where you read the pair itself:

What does this print?
def solve(node):
    take, skip = node["demand"], 0
    for child in node["children"]:
        t, s = solve(child)
        take += s
        skip += max(t, s)
    return take, skip

leaf = lambda d: {"demand": d, "children": []}
star = {"demand": 5, "children": [leaf(2), leaf(2), leaf(2)]}
print(solve(star))

Now it's your turn to break it. Someone "simplified" the take line:

broken — fix it

The best legal plan opens the two ends for 8, but this prints 13, which means all three depots are open, including two linked pairs. Fix the line that lets an open depot count an open child.

Scene 1 of 9
Project context and further resources
You're building a piece ofMeridian — the day planner
This piece — night_depots(): Chooses which depots stay open overnight when neighbouring depots can't both open.
Scenario At night Meridian keeps only some depots open. Two depots joined by a direct road share one night security patrol, so they can't both be open, and every depot has a different overnight demand. The night plan picks the depots that serve the most demand without breaking that rule.
night_depots.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
night_depots(tree) → dictThe largest overnight demand with no two linked depots both open, and which depots open, in pre-order.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.