Lecture 05 - Decrease and Conquer
Lecture 05 - Decrease and Conquer
Solving
Lecture 05 – Problem Solving
using Decrease and Conquer
a b c d
e f g h
e f g h
a b a b
a not a
dag dag
c d c d
Vertices of a dag can be linearly ordered so that for every edge its starting
vertex is listed before its ending vertex (topological sorting). Being a dag
is also a necessary condition for topological sorting to be possible.
Topological Sorting
Example
Order the following items in a food chain
tiger
human
fish
sheep
shrimp
plankton wheat
Decrease-by-Constant-
Factor Algorithms
• In this variation of decrease-and-
conquer, instance size is reduced by the
same factor (typically, 2)
• Examples:
• Binary search and the method of bisection
• Exponentiation by squaring
• Multiplication à la russe (Russian peasant
method)
• Fake-coin puzzle
• Josephus problem
Exponentiation by
Squaring
• The problem: Compute an where n is a
nonnegative integer
• The problem can be solved by applying
recursively the formulas:
For even values of n
a n = (a n/2 )2 if n > 0 and a 0 =
For odd values of n 1
a n
= (a (n-1)/2
)2 a
Recurrence: M(n) = M( n/2 ) + f(n),
where f(n) = 1 or 2,
M(0) = 0
Master Theorem: M(n) Θ(log n) = Θ(b)
where b = log2(n+1)
Russian Peasant
Multiplication
• The problem: Compute the product of two
positive integers Can be solved by a decrease-
by-half algorithm based on the following
formulas.
• For Even Values of n:
n * m = n/2 * 2m
• For Odd values of n:
n * m = (n – 1)/2 * 2m + m, if n > 1 and m if n = 1
Example of Russian
Peasant Multiplication
Compute 20 * 26
n m
20 26
10 52
5 104 104
2 208 +
1 416 416
Fake-Coin Puzzle (simpler
version)
• There are n identically looking coins one of
which is fake.
• There is a balance scale but there are no
weights; the scale can tell whether two sets of
coins weigh the same and, if not, which of the
two sets is heavier (but not by how much, i.e.
3-way comparison).
• Design an efficient algorithm for detecting the
fake coin. Assume that the fake coin is known
to be lighter than the genuine ones.
• Decrease by factor 2 algorithm
Variable-Size-Decrease
Algorithms
• In the variable-size-decrease variation of decrease and-
conquer, instance size reduction varies from one iteration
to another
• Examples:
• Euclid’s algorithm for greatest common divisor
• Partition-based algorithm for selection problem
• Interpolation search
• Some algorithms on binary search trees
• Nim and Nim-like games
Euclid’s Algorithm
• Euclid’s algorithm is based on repeated application of
equality, gcd(m, n) = gcd(n, m mod n)
• Ex:
<k >k
Searching in Binary Search
Tree
Algorithm BST(x, v)
//Searches for node with key equal to v in BST rooted at
node x
if x = NIL return -1
else if v = K(x) return x
else if v < K(x) return BST(left(x), v)
else return BST(right(x), v)
Efficiency
worst case: C(n) = n
average case: C(n) ≈ 2ln n ≈ 1.39log2 n, if the BST was
built from n random keys and v is chosen randomly.
END!