跳到主要内容

算法设计与分析

大学计算机科学知识点 10

本主题的视频课程 打开视频页面
5:37

算法设计与分析

本课程教你在把真实数据交给算法处理之前,先评估其设计的计算代价。前两个单元介绍分析工具和分治法。接下来两个单元介绍两种选择模式:贪心算法和动态规划。最后两个单元探索前沿内容:先是图优化,然后是归约和 NP 完全性。每个论断都用具体输入加以检验。

英文讲解 · 可切换中英文字幕

探索

The same subproblem, again and again

Step through naive fib(5). fib(3) is computed twice and fib(2) three times; a memo table would compute each once, which is the whole idea of dynamic programming.

讲义

English

What this course is, and how to use it

This is the tenth course in University Computer Science: algorithm design and analysis 算法设计与分析. It teaches how to prove what an algorithm costs before you trust it with real data, and a set of design patterns that make those proofs easier.

A limit, stated once: this is a study course, not a degree. Every pseudocode fragment here was checked against a Python version, and every claim about growth was checked on real inputs.

  • Units 10.1–10.2 are the analysis tools and the first pattern: recurrences, and divide and conquer.
  • Units 10.3–10.4 are patterns for making choices: greedy algorithms and dynamic programming.
  • Units 10.5–10.6 are the harder problems: graph optimisation and NP-completeness.

The habit to build: a claim about an algorithm is a proof sketch with numbers. Every unit works through one.

Recurrences and analysis tools

Why it matters. A recursive algorithm states its own cost as a recurrence 递推式. If you can read a recurrence, you can price a design before you write it.

The idea. Take $T(n) = 2T(n/2) + \Theta(n)$. A recursion tree 递归树 shows the work at each level:

  • level $i$ has $2^i$ nodes, each of size $n/2^i$, so each level costs $\Theta(n)$;
  • there are $\log_2 n$ levels.

So $T(n) = \Theta(n \log n)$. This is the cost of merge sort, read straight from a picture.

Recursion tree
Each level of the tree costs the same n; the depth is log₂ n — the product is the answer

The master method. For $T(n) = aT(n/b) + f(n)$, compare $f(n)$ (the work at the root) with $n^{\log_b a}$ (the total work at the leaves):

case result
$f(n)=O(n^{\log_b a-\epsilon})$ for some $\epsilon>0$ $T = \Theta(n^{\log_b a})$
$f(n)=\Theta(n^{\log_b a})$ $T = \Theta(f(n) \log n)$
$f(n)=\Omega(n^{\log_b a+\epsilon})$ for some $\epsilon>0$, and $af(n/b)\leq cf(n)$ for some $c<1$ and sufficiently large $n$ $T = \Theta(f(n))$

Course cases:

  • $2T(n/2) + n$: balanced, so $n \log n$;
  • $T(n/2) + 1$: balanced (binary search), so $\log n$;
  • $4T(n/2) + n$: the leaves give $n^{\log_2 4} = n^2$, which is bigger, so $n^2$.

Worked example 1: proof by substitution. For $T(n) = 2T(n/2) + n$, guess $T(n) \le c\,n\log_2 n$. Substitute the guess for the smaller problems:

$$2c\,\frac{n}{2}\log_2\frac{n}{2} + n = cn\log_2 n - cn + n \le cn\log_2 n \quad\text{when } c \ge 1$$

The induction works, so the guess is proved, not just assumed.

Worked example 2: measuring, not guessing. A merge sort that counts its comparisons makes $\mathbf{310}$ comparisons on the fixed 64-element course array. The worst-case limit is $n\log_2 n - n + 1 = 384 - 64 + 1 = 321$. The measured number falls inside the predicted family: that is the honest check.

Common mistakes.

  • Adding up the leaves but not the levels, or the other way round.
  • Using the master method for unequal splits such as $T(n/3) + T(2n/3)$. Draw the tree instead.
  • Thinking a tighter loop changes the recurrence. The work function is what it is.

Summary. Draw the tree, add up the levels, count the depth. The master method compares the root's work with the leaves' total. Substitution proves the closed form, and measurement checks it.

Divide and conquer

Why it matters. Split, solve, combine: this pattern is behind merge sort, quicksort, binary search and Strassen's matrix multiplication. The skill is pricing the combine step honestly.

The idea.

  • Merge sort 归并排序 splits in half, sorts each half recursively and merges in $\Theta(n)$: $T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n)$.
  • Quicksort 快速排序 partitions around a pivot first. The work moves into the partition, and the quality of the split decides everything.
Recursion structure
The same skeleton with three combine costs: merging (n per level), comparing (n per level), a constant — three different bills

Quicksort's three cases.

  • Balanced pivots: $T(n) = 2T(n/2) + \Theta(n) = \Theta(n \log n)$.
  • Sorted input, with the first element as pivot: $T(n) = T(n-1) + \Theta(n) = \Theta(n^2)$, because each partition removes only one element.
  • Random pivots: about $2n\ln n \approx 1.39\,n\log_2 n$ comparisons on average.

On the course array, quicksort makes $\mathbf{356}$ comparisons against merge sort's 310: the same family, with a different constant.

Worked example 1: the maximum subarray. Split the array in half. The best subarray is either the best one on the left, the best one on the right, or the best one that crosses the middle (a piece ending at the middle plus a piece starting there). Finding the crossing one takes a full pass, so $T(n) = 2T(n/2) + \Theta(n) = \Theta(n\log n)$. On the course array $[-2, 1, -3, 4, -1, 2, 1, -5, 4]$, the best is $[4, -1, 2, 1]$, with sum $6$.

Worked example 2: binary search as the simplest case. One recursive call and a constant combine step: $T(n) = T(n/2) + \Theta(1) = \Theta(\log n)$. The pattern still works with only one branch: divide and conquer does not need two.

Common mistakes.

  • Charging the combine cost at the leaves instead of at each level.
  • Assuming balanced splits for quicksort without random pivots.
  • Forgetting the cost of the recursion itself on tiny subproblems. Real implementations switch to insertion sort below about 16 elements for exactly this reason.

Summary. Split, solve, combine; the recurrence prices the combine step. Quicksort's cost depends on the pivots. One branch is still the same pattern (binary search).

Greedy algorithms

Why it matters. The greedy choice, "take the best option now", is the cheapest design there is. The whole skill is proving when cheap is also correct.

The idea. A greedy algorithm 贪心算法 builds the solution one piece at a time, always taking the piece that looks best right now. Exchange arguments 交换论证 prove that it is correct: any optimal solution can be changed into the greedy one without getting worse.

Greedy decision diagram
Activity selection: earliest finish first — taking the earliest-finishing activity leaves the most room, and the exchange argument shows any optimal schedule can be made to start the same way

The exchange argument, once. In activity selection, the greedy rule is "choose the activity that finishes earliest". Let $G_1$ be the greedy's first choice and $O_1$ the first activity in some optimal schedule. Then finish($G_1) \le$ finish($O_1$), so replacing $O_1$ with $G_1$ keeps the schedule valid. Repeat this down the list, and the optimal schedule turns into the greedy one with the same number of activities. Greedy is optimal because an optimal solution can always afford greedy's choice.

Worked example 1: activity selection. The course activities (start, finish): (1,4), (3,5), (0,6), (5,7), (3,9), (5,9), (6,10), (8,11), (8,12), (2,14), (12,16).

  • Earliest finish first picks (1,4), (5,7), (8,11), (12,16): four activities.
  • Earliest start first picks (0,6), (6,10), (12,16): only three.

So the greedy rule is a design decision, and only a rule with an exchange proof can be trusted. (Latest start first is the mirror image of earliest finish first, and is also optimal.)

Worked example 2: Huffman coding, greedy with a proof. Letter frequencies $5, 9, 12, 13, 16, 45$ (out of 100). Merge the two smallest again and again:

  1. $5 + 9 = 14$;
  2. $12 + 13 = 25$;
  3. $14 + 16 = 30$;
  4. $25 + 30 = 55$;
  5. $45 + 55 = 100$.

The total code length is the sum of the merged values: $14 + 25 + 30 + 55 + 100 = \mathbf{224}$ bits, against $\lceil\log_2 6\rceil \times 100 = 3 \times 100 = 300$ bits for a fixed-length code. An exchange argument (swapping two leaves can only make the cost higher) proves that 224 is the minimum.

Common mistakes.

  • Using greedy where the exchange argument fails. With coins 1, 3 and 4 and a target of 6, greedy pays $4 + 1 + 1$ (three coins); the best is $3 + 3$ (two coins).
  • Mixing up "greedy is optimal" with "greedy is good enough". An approximation is a different promise.
  • Forgetting to sort first. The rule only means something once the items are in the right order.

Summary. Greedy takes the best option now. The exchange argument proves that an optimal solution can afford that choice. The choice rule is the design; where no exchange argument works, greedy is only a heuristic.

Dynamic programming

Why it matters. When subproblems overlap, divide and conquer solves the same ones again and again. Dynamic programming remembers them, which turns exponential work into polynomial work.

The idea. Dynamic programming 动态规划 solves each subproblem once, stores the answer, and builds bigger answers from stored ones. The DP table DP 表 and its dependency order 依赖顺序 (which cells must be filled before which) are the whole design.

DP table
Fibonacci by table: each cell reads the two below it — the dependency order is bottom-up, and memoisation would discover the same order lazily

Why remembering helps so much. The plain recursive Fibonacci function computes $F(n-2)$ twice, $F(n-3)$ three times and $F(n-4)$ five times. The number of calls follows the same kind of recurrence, $C(n) = C(n-1) + C(n-2) + 1$, so it grows exponentially. Memoisation (storing each answer) leaves only $n$ different subproblems: $\Theta(n)$ time and $\Theta(n)$ space. For $F(30)$, the plain version makes $\mathbf{2{,}692{,}537}$ calls; the memoised one computes $30$ values.

Worked example 1: tables by hand.

  • Fibonacci, six cells: 1, 1, 2, 3, 5, 8.
  • The coin problem (coins 1, 3, 4; target 6): $dp[0] = 0$, and $dp[i] = 1 + \min(dp[i - c])$ over the coins $c$ that fit.
$i$ 0 1 2 3 4 5 6
$dp[i]$ 0 1 2 1 1 2 2

So $dp[6] = 2$ ($3 + 3$), not greedy's 3.

Worked example 2: a small, exact knapsack. Capacity 7; items (weight, value): (1, 1), (3, 4), (4, 5), (5, 7). Filling the table over capacities gives $dp[7] = 9$: items 2 and 3, total weight 7, total value 9. (The next best, items 1 and 4, has weight 6 and value 8.) Every cell is a decision with a reason, so the table is also the explanation.

Common mistakes.

  • Writing the recurrence without the base cases.
  • Filling the table in an order that reads cells not yet written. The fill order is part of the design.
  • Memoising a function whose result depends on more than its arguments. The stored answers would then be wrong.

Summary. Overlapping subproblems plus optimal substructure: fill a table or memoise. The recurrence, the base cases and the fill order are the design, and the table also explains the answer.

Graph optimisation

Why it matters. Shortest paths, spanning trees and flows are the questions that roads, networks and power grids are built on. Each has an algorithm, and whether it is greedy or DP explains its speed.

The idea.

  • Dijkstra's algorithm (from unit 9.3): greedy, always settle the nearest node; $O((V + E)\log V)$ with a heap.
  • Kruskal's algorithm 克鲁斯卡尔: sort the edges and accept each edge that joins two separate components. It is greedy over the sorted list, with a union-find structure to detect cycles.
  • Cuts 割 give the proofs: the lightest edge crossing a cut is always safe to accept.
Graph cuts
A cut separates visited from unvisited; the light edge crossing it is safe — the property behind both Dijkstra and Kruskal

The light-edge argument. Take any cut of the graph (a split of the nodes into two groups), and let $e$ be the lightest edge crossing it. Some minimum spanning tree contains $e$:

  1. Take any spanning tree $T$ that does not contain $e$.
  2. Add $e$. This makes a cycle, which must cross the cut again at some other edge $e'$, with weight $\ge$ the weight of $e$.
  3. Remove $e'$. The result is a spanning tree that is no heavier than $T$.

So greedy never makes a choice it cannot recover from. This argument supports Kruskal’s and Prim’s algorithms. Dijkstra’s settle step instead relies on nonnegative edge weights and shortest-path distances.

Worked example 1: Kruskal on the course graph. The edges in sorted order:

edge weight decision
C–B 1 accept
A–C 2 accept
D–E 2 accept
E–F 3 accept
A–B 4 reject (A and B are already joined through C)
B–D 5 accept (joins the two groups)
D–F 6 reject (cycle)
C–D 8 reject (cycle)
C–E 10 reject (cycle)

The result is a minimum spanning tree with 5 edges and weight $1 + 2 + 2 + 3 + 5 = 13$.

Worked example 2: where greedy fails, negative weights. Dijkstra's algorithm settles a node and never looks at it again. Take the edges A→B (2), A→C (5) and C→B (−4). Dijkstra settles B at distance 2, because it is the nearest. But the path through C reaches B at $5 - 4 = 1$. The light-edge guarantee needs weights that are not negative. With negative weights, the Bellman-Ford algorithm, with up to $V-1$ rounds of edge relaxations, taking $O(VE)$ time, is the right tool, and it also detects negative cycles that greedy cannot see.

Common mistakes.

  • Running Dijkstra's algorithm on a graph with negative edges.
  • Leaving out Kruskal's cycle check. Accepting an edge that closes a cycle breaks the tree.
  • Calculating the weight of a spanning tree from node distances instead of adding up its edges.

Summary. Cuts and light edges prove the greedy graph algorithms. Dijkstra needs weights that are not negative. Kruskal = sort, then reject cycles. Negative edges need Bellman-Ford.

Reductions and NP-completeness

Why it matters. Some problems are provably hard, and the proof is a reduction 归约: showing that one problem is another problem in disguise. Knowing the list of hard problems stops you from trying to solve one of them by accident.

The idea. $A \le_p B$ ("$A$ reduces to $B$") means there is a polynomial-time translator that turns any instance of $A$ into an instance of $B$, so a solver for $B$ also solves $A$. NP-completeness NP 完全性: a problem is NP-complete if it is in NP and every problem in NP reduces to it. These are the hardest problems in NP.

Reduction map
The reduction map: SAT reduces to 3-SAT reduces to CLIQUE reduces to VERTEX-COVER — solve one and you solve the chain

The two-step hardness proof. To prove that $B$ is NP-hard:

  1. choose a problem $A$ already known to be NP-complete;
  2. build a polynomial-time translator from $A$ to $B$.

Then a polynomial-time solver for $B$ would give one for $A$, and so (by the chain of reductions) one for SAT, which would mean P = NP. The direction matters: you reduce the problem already known to be hard to your new problem. The difficulty flows into the new problem.

Worked example 1: vertex cover from clique. CLIQUE($G$, $k$) asks: does $G$ have $k$ nodes that are all joined to each other? Reduce it to VERTEX-COVER($\bar{G}$, $n - k$), where $\bar{G}$ is the complement of $G$ (it has exactly the edges that $G$ lacks). A $k$-clique in $G$ has no edges between its nodes in $\bar{G}$, so the other $n - k$ nodes touch every edge of $\bar{G}$.

Course case: $G$ is the triangle ABC plus a separate node D, so it has a 3-clique. The edges of $\bar{G}$ are exactly A–D, B–D and C–D, and the set {D}, of size $n - k = 4 - 3 = 1$, covers all of them. The translator is "take the complement of the graph": it runs in polynomial time, and one sentence proves it correct. This is a model reduction.

Left, graph G with the triangle A, B, C highlighted as a 3-clique and D isolated. An arrow labelled complement, linear time, leads to the complement graph, whose only edges join D to A, B and C, so the single node D is a vertex cover of size n minus k equals 1
Complement the graph: a k-clique becomes an (n − k) vertex cover

Worked example 2: what a reduction is not. Reducing your problem to SAT ("I wrote it as a SAT problem") proves nothing about how hard your problem is: the arrow points the easy way. The chain on the course map goes the right way: SAT → 3-SAT (splitting long clauses), 3-SAT → CLIQUE (a gadget for each clause), CLIQUE → VERTEX-COVER (the complement). The difficulty flows outwards from SAT, and each translator runs in polynomial time by construction.

Common mistakes.

  • Reversing the reduction arrow. This is the most common exam error in the subject.
  • Thinking NP means "not polynomial". It means "a solution can be checked in polynomial time"; P is inside NP.
  • Calling a problem NP-complete without checking that it is in NP.

Summary. $A \le_p B$: a polynomial translator turns a solver for $B$ into a solver for $A$. NP-complete = in NP + NP-hard. Prove hardness by reducing a known hard problem to yours: the arrow carries the difficulty.

词汇
English 中文 拼音
algorithm design and analysis/ˈælɡərɪθəm dɪˈzaɪn ænd əˈnæləsɪs/ 算法设计与分析 suàn fǎ shè jì yǔ fēn xī
recurrence/rɪˈkʌrəns/ 递推式 dì tuī shì
recursion tree/rɪˈkɜːʃn triː/ 递归树 dì guī shù
merge sort/mɜːdʒ sɔːt/ 归并排序 guī bìng pái xù
quicksort/ˈkwɪksɔːt/ 快速排序 kuài sù pái xù
greedy algorithm/ˈɡriːdi ˈælɡərɪθəm/ 贪心算法 tān xīn suàn fǎ
exchange argument/eksˈtʃeɪndʒ ˈɑːɡjuːmənt/ 交换论证 jiāo huàn lùn zhèng
dynamic programming/daɪˈnæmɪk ˈprəʊɡræmɪŋ/ 动态规划 dòng tài guī huà
DP table/ˌdiː ˈpiː ˈteɪbl/ DP 表 DP biǎo
dependency order/dɪˈpendənsi ˈɔːdə/ 依赖顺序 yī lài shùn xù
Kruskal/ˈkrʌskl/ 克鲁斯卡尔 kè lǔ sī kǎ ěr
cuts/kʌts/ 割 gē
reduction/rɪˈdʌkʃn/ 归约 guī yuē
NP-completeness/ˌen ˈpiː kəmˈpliːtnəs/ NP 完全性 NP wán quán xìng

该知识点的互动课程

逐步完成,配合即时检查练习。

更多 大学计算机科学 知识点

IGCSE, A-Level & AP