Docsity

Reducing Problems: Subset Sum and Longest Increasing Subsequence, Study notes of Computer Science

Toggle sidebar
bg1
CS 373 Lecture 2: Reductions and Recursion Fall 2005
Our life is frittered away by detail.
Simplify, simplify.
— Henry David Thoreau
When you come to a fork in the road, take it.
— Yogi Berra
2 Reductions and Recursion (September 6 and 8)
2.1 Reductions
Reduction is the single most common technique used in designing algorithms. Reducing one prob-
lem Xto another problem (or set of problems) Ymeans to write an algorithm for X, using an
algorithm or Yas a subroutine or black box. For example, the congressional apportionment al-
gorithm described in the previous lecture reduces the problem of apportioning Congress to the
problem of maintaining a priority queue under the operations Insert and ExtractMax. In this
class, we’ll generally treat primitive data structures like arrays, linked lists, stacks, queues, hash
tables, binary search trees, and priority queues as black boxes, adding them to the basic vocabulary
of our model of computation. When we design algorithms, we may not know—and we should not
care—how these basic building blocks will actually be implemented.
In some sense, every algorithm is simply a reduction to some underlying model of computation.
Whenever you write a C program, you’re really just reducing some problem to the “simpler”
problems of compiling C, allocating memory, formatting output, scheduling jobs, and so forth. Even
machine language programs are just reductions to the hardware-implemented problems of retrieving
and storing memory and performing basic arithmetic. The underlying hardware implementation
reduces those problems to timed Boolean logic; low-level hardware design reduces Boolean logic
to basic physical devices such as wires and transistors; and the laws of physics reduce wires and
transistors to underlying mathematical principles. At least, that’s what the people who actually
build hardware have to assume.1
2.2 Subset Sum
Let’s start with a concrete example, the subset sum problem: Given a set Xof positive integers and
target integer T, is there a subset of element sin Xthat add up to T? Suppose we have an black
box that can tell us immediately whether such a subset exists. How quickly could we construct
such a subset, using this black box as a subroutine? Notice that there can be more than one such
subset. For example, given the inputs X={8,6,7,5,3,10,9}and T= 15, we could return {8,7}
or {7,5,3}or {6,9}or {5,10}.2
There are two trivial cases. If the target value Tis zero, then we can immediately return the
empty set. On the other hand, if our black box says that no subset exists with the target sum, we
can abort immediately. For the general case, consider an arbitrary element x∈X. (If Xis empty
1The situation is exactly analogous to that of mathematical proof. Normally, when we prove a theorem, we
implicitly rely on a several earlier results. These eventually trace back to axioms, definitions, and the rules of logic,
but it is extremely rare for any proof to be expanded to pure symbol manipulation. Even when proofs are written
in excruciating Bourbakian formal detail, the accuracy of the proof depends on the consistency of the formal system
in which the proof is written. This consistency is simply taken for granted. In some cases (for example, first-order
logic and the first-order theory of the reals) it is possible to prove consistency, but this consistency proof necessarily
(thanks be to G¨odel) relies on some different formal system (usually some extension of Zermelo-Fraenkel set theory),
which is itself assumed to be consistent. It’s turtles all the way down.
2See http://www.cribbage.org/rules/ for more possibilities.
1
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Reducing Problems: Subset Sum and Longest Increasing Subsequence and more Study notes Computer Science in PDF only on Docsity!

Our life is frittered away by detail. Simplify, simplify. — Henry David Thoreau When you come to a fork in the road, take it. — Yogi Berra

2 Reductions and Recursion (September 6 and 8)

2.1 Reductions

Reduction is the single most common technique used in designing algorithms. Reducing one prob- lem X to another problem (or set of problems) Y means to write an algorithm for X, using an algorithm or Y as a subroutine or black box. For example, the congressional apportionment al- gorithm described in the previous lecture reduces the problem of apportioning Congress to the problem of maintaining a priority queue under the operations Insert and ExtractMax. In this class, we’ll generally treat primitive data structures like arrays, linked lists, stacks, queues, hash tables, binary search trees, and priority queues as black boxes, adding them to the basic vocabulary of our model of computation. When we design algorithms, we may not know—and we should not care—how these basic building blocks will actually be implemented. In some sense, every algorithm is simply a reduction to some underlying model of computation. Whenever you write a C program, you’re really just reducing some problem to the “simpler” problems of compiling C, allocating memory, formatting output, scheduling jobs, and so forth. Even machine language programs are just reductions to the hardware-implemented problems of retrieving and storing memory and performing basic arithmetic. The underlying hardware implementation reduces those problems to timed Boolean logic; low-level hardware design reduces Boolean logic to basic physical devices such as wires and transistors; and the laws of physics reduce wires and transistors to underlying mathematical principles. At least, that’s what the people who actually build hardware have to assume.^1

2.2 Subset Sum

Let’s start with a concrete example, the subset sum problem: Given a set X of positive integers and target integer T , is there a subset of element sin X that add up to T? Suppose we have an black box that can tell us immediately whether such a subset exists. How quickly could we construct such a subset, using this black box as a subroutine? Notice that there can be more than one such subset. For example, given the inputs X = { 8 , 6 , 7 , 5 , 3 , 10 , 9 } and T = 15, we could return { 8 , 7 } or { 7 , 5 , 3 } or { 6 , 9 } or { 5 , 10 }.^2 There are two trivial cases. If the target value T is zero, then we can immediately return the empty set. On the other hand, if our black box says that no subset exists with the target sum, we can abort immediately. For the general case, consider an arbitrary element x ∈ X. (If X is empty

(^1) The situation is exactly analogous to that of mathematical proof. Normally, when we prove a theorem, we implicitly rely on a several earlier results. These eventually trace back to axioms, definitions, and the rules of logic, but it is extremely rare for any proof to be expanded to pure symbol manipulation. Even when proofs are written in excruciating Bourbakian formal detail, the accuracy of the proof depends on the consistency of the formal system in which the proof is written. This consistency is simply taken for granted. In some cases (for example, first-order logic and the first-order theory of the reals) it is possible to prove consistency, but this consistency proof necessarily (thanks be to G¨odel) relies on some different formal system (usually some extension of Zermelo-Fraenkel set theory), which is itself assumed to be consistent. It’s turtles all the way down. (^2) See http://www.cribbage.org/rules/ for more possibilities.

and T = 0, we’ve already returned the empty set. If X is empty and T 6 = 0, then no subset of X sums to T , so we’ve already aborted. Thus, X is not empty.) We have two different ways to proceed.

  • Ask the black box if any subset of X \ {x} sums to T. If the answer is no, then every subset of X that sums to T must include the element x. Otherwise, we can safely discard x.
  • Ask the black box if any subset of X \ {x} sums to T − x. If the answer is no, then every subset of X that sums to T must exclude the element x. In this case, we simply discard x. Otherwise, we can safely assume that x is in our desired subset.

If we decide the x is in our output subset, we record this fact and decrease the target sum by x. Then, no matter what we decided, we remove x from the set and recurse. The resulting algorithm(s) look(s) like this:

ConstructSubset(X[1 .. n], T ): if T = 0 return ∅ else if ¬ExistsSubset(X[1 .. n], T ) return Null j ← 0 for i ← 1 to n if (one of)

{ ExistsSubset(X[i + 1 .. n], T − X[i]) ¬ExistsSubset(X[i + 1 .. n], T ) j ← j + 1 Y [j] ← X[i] T ← T − X[i] return Y [1 .. j]

Both versions of the algorithm make at most n calls to the ExistsSubset subroutine in the worst case. The algorithm might be faster if T is small or if the elements of A are large, but that doesn’t matter. Algorithms are usually—and always in this class—analyzed in terms of their worst-case behavior. Now let’s turn the problem around. Suppose we are given a black box ConstructSubset(X, T ) that constructs a subset of X that sums to T. Now deciding whether such a subset exists is completely trivial: if ConstructSubset succeeds, return True, else return False. The existence algorithm makes only one call to the construction subroutine.

2.3 Recursion!

But (I’m sure you can see where this is going) if we try to put these two reductions together into a single algorithm, we end up in an infinite loop: ConstructSubset calls ExistsSubset, which calls ConstructSubset, which calls ExistsSubset, round and round, and nothing every actually gets done. To break out of this infinite loop, what we need to do is make something smaller, so that eventually the cascade will always reach a trivial base case. For example, in or implementation of ExistsSubset, we can remove one element of the set before calling the construction subroutine. Of course, wee can’t do this if the set is already empty, so we’d better handle that case directly. While we’re at it, let’s handle a couple of other trivial cases, too.

ConstructSubset(X[1 .. n], T ): if T = 0 return ∅ if T < 0 or n = 0 return None Y ← ConstructSubset(X[2 .. n], T ) if Y 6 = None return Y Y ← ConstructSubset(X[2 .. n], T − X[1]) if Y 6 = None return Y ∪ {X[1]} return None

2.4 Longest Increasing Subsequence

Suppose we want to find the longest increasing subsequence of a sequence of n integers. That is, we are given an array A[1 .. n] of integers, and we want to find the longest sequence of indices 1 ≤ i 1 < i 2 < · · · ik ≤ n such that A[ij ] < A[ij+1] for all j. To derive a recursive algorithm for this problem, we start with a recursive definition of the kind of object we’re looking for: a sequence of integers.

A sequence of integers is either nothing or an integer followed by a sequence of integers.

This definition immediately suggests a recursive definition for a “best” sequence of integers.

The best sequence of integers is either nothing or the best, over all integers x, of x followed by the best sequence of integers that can follow x.

This is actually not quite a recursive definition; we’ve defined best sequence in terms of best sequence that can follow x, not in terms of itself. Fortunately, it’s fairly easy to extend the algorithm so that it is truly recursive.

The best sequence of integers that can follow x is either nothing or the best, over all integers y that can follow x, of y followed by the best sequence of integers that can follow x.

Or if you prefer formulas to English:

Sequence =

∅ or Integer · Sequence

BestSequenceAfter(x) =

∅ or best{y · BestSequenceAfter(y) | y can follow y}

This recursive definition does not specify the set from which we can choose x and y, and it leaves the notions “best” and “can follow” undefined. These details clearly depend on the specific problem at hand. For the longest increasing subsequence problem, we can fill in these details as follows:

  • The elements are taken from the input array A[1 .. n].
  • One sequence is better than another if it has more elements.
  • An element A[j] can follow A[i] if and only if j > i and A[j] > A[i].

Mechanically plugging these details back into our recursive definition gives us the following algorithm. (This algorithm only computes the length of the longest increasing subsequence, but it is fairly easy to modify the algorithm to compute the sequence itself.)

〈〈Find the longest increasing subsequence of A.〉〉 LIS(A[1 .. n]): max ← 0 for i ← 1 to n L ← 1 + LISafter(A[i], A[i + 1 .. n]) if L > max max ← L return max 〈〈Find the longest increasing subsequence of A that can follow x.〉〉 LISafter(x, A[1 .. n]): max ← 0 for i ← 1 to n if A[i] > x L ← 1 + LISafter(A[i], A[i + 1 .. n]) if L > max max ← L return max Now that we have the algorithm, we can simplify it in a couple of different ways. First, notice that every call to LISafter has the form LISafter(A[i], A[i + 1 .. n]). We’re really just passing in the subarray A[i .. n], but with the first element separated; the algorithm becomes slightly simpler if we don’t make this artificial separation. Second, the two algorithms are almost identical; we can make them exactly identical by adding a sentinel value −∞ to the start of the array.

LIS(A[1 .. n]): A[0] ← −∞ return LISafter(A[0 .. n])

LISafter(A[0 .. n]): max ← 0 for i ← 1 to n if A[i] > x L ← 1 + LISafter(A[i .. n]) if L > max max ← L return max

Let T (n) denote the running time of LISafter; the running time of LIS is clearly T (n) + O(1). Reading directly from the algorithm, we derive the following recurrence for T (n):

T (n) = Θ(n) +

∑^ n

i=

T (n − i) = Θ(n) +

n∑− 1

j=

T (j)

This is only an upper bound. We can’t predict in advance how many recursive calls LISafter will make, so we simply assume the worst. To get a solution, we first transform it from a ’full history

2.6 3SAT

Now let’s consider the mother of all NP-hard problems, 3SAT. Given a boolean formula in conjunc- tive normal form, with at most three literals in each clause, our task is to determine whether any assignment of values of the variables makes the formula true. Yes, this problem is NP-hard, which means that a polynomial algorithm is almost certainly impossible. Too bad; we have to solve the problem anyway. The trivial solution is to try every possible assignment. We’ll evaluate the running time of our 3SAT algorithms in terms of the number of variables in the formula, so let’s call that n. Provided any clause appears in our input formula at most once—a condition that we can easily enforce in polynomial time—the overall input size is O(n^3 ). There are 2n^ possible assignments, and we can evaluate each assignment in O(n^3 ) time, so the overall running time is O(2nn^3 ). Since polynomial factors like n^3 are essentially noise when the overall running time is expo- nential, from now on I’ll use poly(n) to represent some arbitrary polynomial in n; in other words, poly(n) = nO(1). For example, the trivial algorithm for 3SAT runs in time O(2n^ poly(n)). We can make this algorithm smarter by exploiting the special recursive structure of 3CNF formulas:

A 3CNF formula is either nothing or a clause with three literals ∧ a 3CNF formula

Suppose we want to decide whether some 3CNF formula Φ with n variables is satisfiable. Of course this is trivial if Φ is the empty formula, so suppose

Φ = (x ∨ y ∨ z) ∧ Φ′

for some literals x, y, z and some 3CNF formula Φ′. By distributing the ∧ across the ∨s, we can rewrite Φ as follows: Φ = (x ∧ Φ′) ∨ (y ∧ Φ′) ∨ (z ∧ Φ′)

For any boolean formula Ψ and any literal x, let Ψ|x (pronounced “sigh given eks”) denote the simpler boolean formula obtained by assuming x is true. It’s not hard to prove by induction (hint, hint) that x ∧ Ψ = x ∧ Ψ|x, which implies that

Φ = (x ∧ Φ′|x) ∨ (y ∧ Φ′|y) ∨ (z ∧ Φ′|z).

Thus, in any satisfying assignment for Φ, either x is true and Φ′|x is satisfiable, or y is true and Φ′|y is satisfiable, or z is true and Φ′|z is satisfiable. Each of the smaller formulas has at most n − 1 variables. If we recursively check all three possibilities, we get the running time recurrence

T (n) ≤ 3 T (n − 1) + poly(n),

whose solution is O(3n^ poly(n)). So we’ve actually done worse! But these three recursive cases are not mutually exclusive! If Φ′|x is not satisfiable, then x must be false in any satisfying assignment for Φ. So instead of recursively checking Φ′|y in the second step, we can check the even simpler formula Φ′|¯xy. Similarly, if Φ′|xy¯ is not satisfiable, then we know that y must be false in any satisfying assignment, so we can recursively check Φ′|¯xyz¯ in the third step.

3sat(Φ): if Φ = ∅ return True (x ∨ y ∨ z) ∧ Φ′^ ← Φ if 3sat(Φ|x) return True if 3sat(Φ|¯xy) return True return 3sat(Φ|x¯¯yz)

The running time off this algorithm obeys the recurrence

T (n) = T (n − 1) + T (n − 2) + T (n − 3) + poly(n),

where poly(n) denotes the polynomial time required to simplify boolean formulas, handle control flow, move stuff into and out of the recursion stack, and so on. The annihilator method gives us the solution T (n) = O(λn^ poly(n)) = O(1. 83928675522 n)

where λ ≈ 1. 83928675521... is the largest root of the characteristic polynomial r^3 − r^2 − r − 1. (Notice that we cleverly eliminated the polynomial noise by increasing the base of the exponent ever so slightly.) We can improve this algorithm further by eliminating pure literals from the formula before recursing. A literal x is pure in if it appears in the formula Φ but its negation ¯x does not. It’s not hard to prove (hint, hint) that if Φ has a satisfying assignment, then it has a satisfying assignment where every pure literal is true. If Φ = (x ∨ y ∨ z) ∧ Φ′^ has no pure literals, then some in Φ contains the literal ¯x, so we can write

Φ = (x ∨ y ∨ z) ∧ (¯x ∨ u ∨ v) ∧ Φ′

for some literals u and v (each of which might be y, ¯y, z, or ¯z). It follows that the first recursive formula Φ|x has contains the clause (u ∨ v). We can recursively eliminate the variables u and v just as we tested the variables y and x in the second and third cases of our previous algorithm:

Φ|x = (u ∨ v) ∧ Φ′|x = (u ∧ Φ′|xu) ∨ (v ∧ Φ′|xuv¯ ).

Here is our new faster algorithm:

3sat(Φ): if Φ = ∅ return True if Φ has a pure literal x return 3sat(Φ|x) (x ∨ y ∨ z) ∧ (¯x ∨ u ∨ v) ∧ Φ′^ ← Φ if 3sat(Φ|xu) return True if 3sat(Φ|xuv¯) return True if 3sat(Φ|¯xy) return True return 3sat(Φ|x¯yz¯)

We can improve this bound even more by examining the new worst case: v has exactly one neighbor w. In this case, either v or w appears in any maximal independent set. Thus, instead of recursively searching in G \ {v}, we should recursively search in G \ N (w), which has at most n − 1 nodes. On the other hand, if G has no nodes with degree 1, then G \ N (v) has at most n − 3 nodes.

M (n) ≤ max

M (n − 1) 2 M (n − 2) M (n − 1) + M (n − 3)

= O(1. 46557123188 n)

The base of the exponent is the largest root of the characteristic polynomial r^3 − r^2 − 1. The second case implies a bound of O(

n ) = O(1. 41421356237 n), which is smaller. We can apply this improvement technique one more time. If G has a node v with degree 3 or more, then G \ N (v) has at most n − 4 nodes. Otherwise (since we have already considered nodes of degree 0 and 1), every node in the graph has degree 2. Let u, v, w be a path of three nodes in G (possibly with u adjacent to w). In any maximal independent set, either v is present and u, w are absent, or u is present and its two neighbors are absent, or w is present and its two neighbors are absent. In all three cases, we recursively count maximal independent sets in a graph with n − 3 nodes.

M (n) ≤ max

M (n − 1) 2 M (n − 2) M (n − 1) + M (n − 4) 3 M (n − 3)

= O(3n/^3 ) = O(1. 44224957031 n)

The third case implies a bound of O(1. 3802775691 n), where the base is the largest root of r^4 −r^3 −1. Unfortunately, we cannot apply the same improvement trick again. A graph consisting of n/ 3 triangles (cycles of length three) has exactly 3n/^3 maximal independent sets, so our upper bound is tight in the worst case. Now from this recurrence, we can derive an efficient algorithm to compute the largest indepen- dent set in G in O(3n/^3 poly(n)) = O(1. 44224957032 n) time.

MaximumIndSetSize(G): if G = ∅ return 0 else if G has a node v with degree 0 return 1 + MaximumIndSetSize(G \ {v}) 〈〈n − 1 〉〉 else if G has a node v with degree 1 w ← v’s neighbor withv ← 1 + MaximumIndSetSize(G \ N (v)) 〈〈n − 2 〉〉 withw ← 1 + MaximumIndSetSize(G \ N (w)) 〈〈≤ n − 2 〉〉 return max{withv , withw } else if G has a node v with degree greater than 2 withv ← 1 + MaximumIndSetSize(G \ N (v)) 〈〈≤ n − 4 〉〉 withoutv ← MaximumIndSetSize(G \ {v}) 〈〈≤ n − 1 〉〉 return max{withv , withoutv } else 〈〈every node in G has degree 2 〉〉 v ← any node; u, w ← v’s neighbors withu ← 1 + MaximumIndSetSize(G \ N (u)) 〈〈≤ n − 3 〉〉 withv ← 1 + MaximumIndSetSize(G \ N (v)) 〈〈≤ n − 3 〉〉 withw ← 1 + MaximumIndSetSize(G \ N (w)) 〈〈≤ n − 3 〉〉 return max{withu, withv , withw }

2.8 Generalities

Recursion is reduction from a problem to a simpler instance of the same problem. Almost ev- ery recursive algorithm (and inductive proof) closely follows a recursive definition for the object being computed. Here are a few simple recursive definitions that can be used to derive recursive algorithms:

  • A natural number is either 0 or the successor of a natural number.
  • A sequence is either empty or an atom followed by a sequence.
  • A sequence of length n is either empty, an atom, or a sequence of length bn/ 2 c followed by a sequence of length dn/ 2 e.
  • A set is either the empty set or the union of a set and an atom.
  • A nonempty set either is a singleton or the union of two nonempty sets.
  • A binary tree is either nothing or a node pointing to two binary trees.
  • A full binary tree is either a node, or a node pointing to two full binary trees.
  • A full binary tree is either a node, or a full binary tree with two nodes glued to one of its leaves.
  • A full binary tree is either a node, or a full binary tree where one leaf has been replaced by a full binary tree.
  • A triangulated polygon is nothing, or a triangle glued to a triangulated polygon [not obvious]
  • A triangulated polygon is nothing, or a triangle glued to two triangulated polygons [even less obvious]
  • A non-empty triangulated polygon is a triangle, or two non-empty triangulated polygons glued together along an edge [even less obvious]
  • A string of balanced parentheses is either nothing, or two strings of balanced parentheses, or a string of balanced parentheses inside a pair of parentheses [ S = ε|SS|(S) ]

∑n i=1 ai^ =

0 if n = 0 ∑n− 1 i=1 ai^ +^ an^ otherwise

∑n i=1 ai^ =

0 if n = 0 a 1 if n = 1 ∑bn/ 2 c i=1 ai^ +^

∑n i=bn/ 2 c+1 ai^ otherwise