The divide-and-conquer paradigm involves three steps at each level of the recursion:
Divide the problem into a number of subproblems that are smaller instances of the same problem.
Conquer the subproblems by solving them recursively. If the subproblem sizes are small enough, however, just solve the subproblems in a straightforward manner.
Combine the solutions to the subproblems into the solution for the original problem.
When can we use Divide and Conquer?
Original problem is easily decomposable into subproblems (we don not want to see “overlap” in the subproblems).
Combining solutions is not too costly.
Subproblems are not overly unbalanced.
Example - Counting inversions
Collaborative filtering:
matches users preferences (movies, music, …)
determine users with similar tastes
recommends n ew things to users based on preferences of similar users
Goal: given an unsorted array A[1..n], find the number of inversions in it.
Def
(i,j) is an inversion if i<j and A[i]>A[j]
Example: with A=[1,5,2,6,3,8,7,4], we get
(2,3),(2,5),(2,8),(4,5),(4,8),(6,7),(6,8),(7,8)
Remark: we show the indices where inversions occur
Remark: easy algorithm (two nested loops) in Θ(n2)
random
Idea: solve the problem twice in size 2n (we assume n is a power of 2). Then the optimal subarray (if not empty)
is completely in the left half A[1..n/2]
or is completely in the right half A[n/2+1..n]
or contains bothA[n/2]andA[n/2+1] (cases mutually exclusive)
PQ1
Tower Domination: There are n towers defined by their integer coordinates xi and yi, i=1,2,...,n. We say that a tower idominates a tower if and only if
(xi>xj)∧(yi>yj)∨(xi<xj)∧(yi<yj)
That is, the coordinates of tower i are either both greater, or both smaller, than the coordinates of tower j. Define the dominance factor of tower i as the total number of towers dominated by it. Your task is to design a divide-and-conquer algorithm to compute the dominance factor of each tower.