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 vertices, we can actually compute the largest independent set in time.
Suppose we are given a tree . Without loss of generality, suppose is a rooted tree; that is, there is a special node in called the root, and all edges are implicitly directed away from this vertex. (If is an unrooted tree—a connected acyclic undirected graph—we can choose an arbitrary vertex as the root.) We call vertex a descendant of vertex if the unique path from to the root includes ; equivalently, the descendants of are itself and the descendants of the children of . The subtree rooted at consists of all the descendants of and the edges between them.
For any node in , let denote the size of the largest independent set in the subtree rooted at . Any independent set in this subtree that excludes itself is the union of independent sets in the subtrees rooted at the children of . On the other hand, any independent set that includes necessarily excludes all of ’s children and therefore includes independent sets in the subtrees rooted at ’s grandchildren. Thus, the function obeys the following recurrence, where the nonstandard notation means “ is a child of ”:
We need to compute , where is the root of .
Create a free account to access the full course.
By signing up, you agree to Educative's Terms of Service and Privacy Policy