分治算法
- 基本思想
分而治之:将原始的问题(难以解决的大问题)分解为若干个规模较小的相同的子问题,逐个解决子问题以得到原始问题的解
- 效果
分治策略运用于计算机算法时,往往会出现分解出来的子问题与原始问题类型相同的现象,而与原始问题相比,各个子问题的size变小了,这刚好符合递归的特性。因此,计算机算法中的分治策略往往与递归联系在一起。
- 典型应用
1 最大值最小值问题(引申:寻找第K小的元素)
2 整数乘法问题(二进制)
3 快速傅里叶变换*
4 几种基于分治的排序算法
归并排序
快速排序
————————————————————————————————————————————————————
减治算法
2.1 基本思想
原始问题划分为若干子问题,将原始计算问题转化为其中某一个子问题的计算问题,仅通过求解某一个子问题的解得到原始问题的解
- 算法步骤:
Step 1: Divide S into ⌈n/5⌉ subsets. Each subset contains five elements. Addsome dummy ∞ elements to the last subset if n is not a net multiple of S.
Step 2: Sort each subset of elements.
Step 3: Find the element p which is the median of the medians of the ⌈n/5⌉ subsets.Algorithm of Selection Problem
Step 4: Partition S into S1, S2 and S3, which contain the elements less than,equal to, and greater than p, respectively.
Step 5: If |S1|≥ k, then discard S2 and S3 and solve the problem that selects the kth smallest element from S1 during the next iteration;else if |S1| + |S2|≥ k then p is the kth smallest element of S;otherwise, let k'= k - |S1| - |S2|, solve the problem that selects the k'th smallest element from S3 during the next iteration.
- 典型应用
1 折半查找
2 快速排序(每一次运行一次划分算法都只是排好了一个元素)
3 深度优先查找&广度优先查找
4 拓扑排序
5 插入排序
6 二叉查找树
————————————————————————————————————————————————————
对比:
The divide-and-conquer has three divide,conquer and combine.It must deal with each problems,and combine them finally.But the decrease-and-conquer technique is based on exploring the relationship between a solution to a given instance of a problem and a solution to a smaller instance or of the same problem.It donoy combine them and do not solve each of them.
- For example : compute a^n
the divide-and conquer: compute a^n=a^n/2 * a^n/2.
the decrease-and-conquer: compute a^n={ (a^n/2)*2 if n is oven and positive}
{ (a^n-1/2)^2*2 if n is odd and >1 }
{ a if a=1 }