Dynamic Programming on Trees

Explore the different techniques used to solve the dynamic programming on trees problem efficiently.

Using dynamic programming to solve the largest independent set problem in trees

So far, all of our dynamic programming examples use multidimensional arrays to store the results of recursive subproblems. However, as the next example shows, this is not always the most appropriate data structure to use.

An independent set in a graph is a subset of the vertices with no edges between them. Finding the largest independent set in an arbitrary graph is extremely hard; this is one of the canonical NP-hard problems, but we won’t be studying it in this course. But in some special classes of graphs, we can find the largest independent sets quickly. In particular, when the input graph is a tree with nn vertices, we can actually compute the largest independent set in O(n)O(n) time.

Suppose we are given a tree TT. Without loss of generality, suppose TT is a rooted tree; that is, there is a special node in TT called the root, and all edges are implicitly directed away from this vertex. (If TT is an unrooted tree—a connected acyclic undirected graph—we can choose an arbitrary vertex as the root.) We call vertex ww a descendant of vertex vv if the unique path from ww to the root includes vv; equivalently, the descendants of vv are vv itself and the descendants of the children of vv. The subtree rooted at vv consists of all the descendants of vv and the edges between them.

For any node vv in TT, let MIS(v)MIS(v) denote the size of the largest independent set in the subtree rooted at vv. Any independent set in this subtree that excludes vv itself is the union of independent sets in the subtrees rooted at the children of vv. On the other hand, any independent set that includes vv necessarily excludes all of vv’s children and therefore includes independent sets in the subtrees rooted at vv’s grandchildren. Thus, the function MISMIS obeys the following recurrence, where the nonstandard notation wvw ↓ v means “ww is a child of vv”:

MIS(v)=max{wvMIS(w),1+wv xwMIS(x)}MIS(v) = max \begin{Bmatrix} \underset{w\downarrow v}{\sum}MIS(w), 1+ \underset{w\downarrow v}{\sum} \space\underset{x\downarrow w}{\sum} MIS(x) \end{Bmatrix}

We need to compute MIS(r)MIS(r), where rr is the root of TT.

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy