⭐文章目录⭐
👇
Divide and Conquer
Divide a problem into smaller subproblems, solve each subproblem independently, and then combine the solutions to the subproblems to solve the original problem.
Counting Inversions
Given an array of n distinct integers, count the number of inversions in the array. An inversion is a pair of indices such that and .
Solutions
Bruteforce solution: time complexity.
D&C: O(nlogn) time complexity.
- Divide the array into two halves.
- Count the number of inversions in each half recursively.
- Count the number of inversions in the different halves.
Sort-and-CountInv(A): if n <= 1: return (A,0) else: L=left half of A R=right half of A (B,LInv)=Sort-and-CountInv(L) (C,RInv)=Sort-and-CountInv(R) (D,SInv)=Merge-and-Sort(B,C) return (D,LInv+RInv+SInv) pesudo
Merge-and-Sort(B,C): i=0, j=0, SInv=0 for k in range(n): if B[i] <= C[j]: D[k]=B[i] i=i+1 else: D[k]=C[j] j=j+1 SInv=SInv+n/2-i+1 return (D,SInv) pesudo
We have
Therefore, the time complexity is .
Closest Pair of Points
Given n points in the plane, find the two points that are closest to each other.
Solutions
1.Watching this picture, when we want to find the closest pair in the split part, we first find a point ,whose distance to the cut line is less than .
2.Then we can cut the plane into eight parts of square, and each part can have at most 1 point.
3.Then we only need to find the closest pair in the divided parts and go through all the points whose distance to the cut line is less than .
Px=sort P by X Py=sort P by Y closestPair(Px,Py): if n<=3: return bruteforce(Px) else: Lx= pts on the left half,sorted by X Ly= pts on the left half,sorted by Y Rx= pts on the right half,sorted by X Ry= pts on the right half,sorted by Y (L1,L2)=closestPair(Lx,Ly) (R1,R2)=closestPair(Rx,Ry) d=min(dist(L1,L2),dist(R1,R2)) (s1,s2)= closestSplitPair(Px,Py,d) return the_closest_pair((L1,L2),(R1,R2),(s1,s2)) pesudo
closestSplitPair(Px,Py,d): x'=largest x of Pts in left half S={q1,q2,...,qk}(x'-d <= q <= x'+d)(sorted by y) minDist = +inf for i=1 to k: for j= 1 to 8: if (dist(qi,qi+j) < minDist): minDist=dist(qi,qi+j) closestPair=(qi,qi+j) return closestPair pesudo
The time complexity is .
Time Compute
Solutions
Recursion Tree Method
- If the running time of per level decreases, select the first level.
- If the running time of per level increases, select the last level.
- If the running time of per level is the same, total time=per level time number of levels.
Master Theorem
- If , or , .
- If , or , .
- If , or , .
Enhanced Master Theorem
Substitution Method
Guess and proof.
Preview: