COMP2119A 数据结构与算法问题集

与 OI 中间接接触到的各种 DS&A 知识相比,这门课的优势在于比较正统,严谨的理论分析;因此还是有必要记录一下的。这篇笔记将采用 problem-based 的形式,比较随性的收集一些 insights。

Recursion Problem

关于 Recursion Problem 有大概两种题型:

  • 根据 recurrence equation 求 closed-form。
  • 同时给出 recurrence equation 与 closed-form,证明它们是对应的。

第一种:比较容易的高中数列题。一般来说有两种做法:

  • 根据 recurrence equation,不断将 f(n)f(n) 拆成 f(n−1)f(n-1),寻找一系列表达式之间的规律。
  • 从 base case f(1)f(1) 开始向 f(n)f(n) 累加,累加的值可用等差/等比数列求和简化。

Ex1. perm(A, n, n) is a function outputting all permutations of array AA with a length of nn. Define f(n)f(n) to be the # swap() function get called. Prove that for k>1k>1 we have 2k!≤f(k)≤2ek!2k!\leq f(k)\leq 2ek!.

cpp
void perm(int* A, int k, int n) {
    if (k == 1)	output(A);
    for (int i = 1; i <= k; ++i) {
        swap(A[i], A[k]);
        perm(A, k - 1, n);
        swap(A[i], A[k]);
    }
}
perm(A, n, n);

Ex2. Let L(n)L(n) be the max # of regions formed by nn lines in a plane.

第二种:使用 mathematical induction(M.I.)进行证明。

  • Base case:证明在 nn 的最小值 n0n_0 处成立。
  • Induction hypothesis:列出归纳假设,即对于 S(n0),...,S(k)S(n_0),...,S(k) with k≥n0k\geq n_0 假设成立,则对于 S(k+1)S(k+1) 同样成立。(一般来说直接归纳证明 S(n0+1)S(n_0+1) 成立)
  • Induction step:用等号连接 S(k+1)S(k+1) 的两种表示,证明 LHS=RHSLHS=RHS。

Complexity Analysis

T(n)=Θ(f(n))T(n)=\Theta(f(n)),意味着:

  • T(n)T(n) is bounded by f(n)f(n): ∃c1>0,c2>0,n0>0\exists c_1>0, c_2>0, n_0>0 s.t. ∀n≥n0,0≤c1g(n)≤f(n)≤c2g(n)\forall n\geq n_0,0\leq c_1g(n)\leq f(n)\leq c_2 g(n).
  • T(n)T(n)'s time complexity is f(n)f(n).
  • T(n)T(n)'s order of growth is f(n)f(n).
  • lim⁡n→∞T(n)/f(n)=c\lim_{n\to \infty} T(n)/f(n)=c, cc is a constant.

在比较两算法 execution time T1(n),T2(n)T_1(n), T_2(n) 的 time complexity/order of growth 时常采用取极限的方法:

  • lim⁡n→∞T1(n)/T2(n)=∞\lim_{n\to \infty} T_1(n)/T_2(n)=\infty,T1T_1 在渐进意义下比 T2T_2 增长的更快。
  • lim⁡n→∞T1(n)/T2(n)=c\lim_{n\to\infty}T_1(n)/T_2(n)=c for some constant cc,T1T_1 与 T2T_2 的渐进增长速度一致。
  • lim⁡n→∞T1(n)/T2(n)=0\lim_{n\to\infty}T_1(n)/T_2(n)=0,T2T_2 渐进意义下比 T1T_1 增长的更快。

除 Θ\Theta 之外,还有其他四种常见的 notation,每一种 notation 描述的是 a set of functions:

notations description
Little-Oh o(f(n))o(f(n)) f(n)>T(n)f(n)> T(n), not-asymptotically-tight upper bound
Big-Oh O(f(n))O(f(n)) f(n)≥T(n)f(n)\geq T(n), upper bound
Big-Theta Θ(f(n))\Theta(f(n)) f(n)=T(n)f(n)=T(n), same order of growth
Big-Omega Ω(f(n))\Omega(f(n)) f(n)≤T(n)f(n)\leq T(n), lower bound
Little-Omega ω(f(n))\omega(f(n)) f(n)<T(n)f(n)<T(n), not-asymptotically-tight lower bound

关于 tractable / computationally hard problems:

  • tractable: 存在 worst-case polynomial-time 的算法,i.e., O(nc)O(n^c) for some constant cc.
  • computationally hard: worst-case complexity is O(rn)O(r^n) for some r>1r>1.

有关时间复杂度分析的几种题型:

  • 比较一系列 total execution time 之间的渐进增长速度。
  • 分析 recursive function 的时间复杂度。

第一种:相除后取极限进行比较。

  • Ex1. 比较 log⁡n3.14log⁡n\sqrt{\log{n}}^{3.14\log{n}} 与 2n8+log⁡2n+12n^8+\log^2{n}+1.(Ans 1>21>2)
  • Ex2. 比较 log⁡5(n!)\log_5(n!) 与 log⁡7(nn)\log_7(n^n).(Ans 1=21=2, log⁡5(n!)=log⁡7(nn)=Θ(nlog⁡n)\log_5(n!)=\log_7(n^n)=\Theta(n\log{n}))
  • Ex3. (midterm)

第二种:使用 Master Theorem 进行分析。

Amortized/Average Analysis

以 hash table 为例,讲下如何进行时间复杂度的均摊分析。

若 hash table 的容量为 mm,储存了 nn 个元素,我们定义其 load factor α=n/m\alpha=n/m。

  • chaining (open hashing): # of trials ≈1+a2\approx 1+\frac{a}{2}.
  • probing (open addressing): # of trials ≈11−α\approx \frac{1}{1-\alpha}.

可以发现,对于 open addressing 实现的哈希表,我们需要控制 α<12\alpha<\frac{1}{2} 来保证常数级别的单次操作复杂度。这就牵扯到了均摊时间复杂度分析的问题:

  • 当 # of elements ≤m2\leq \frac{m}{2} 时,单次插入/查找的平均时间复杂度为 O(1)O(1)。
  • 当 # of elements reach m2\frac{m}{2},重建一个容量为 2m2m 的哈希表,时间复杂度为 O(m)O(m)。

在所有插入操作中,只有极小部分会 trigger 哈希表的重建:我们考虑将代价较大的哈希表的重建操作均摊到所有插入操作的代价中。设插入一次的时间代价为 cc,因为哈希表重建而均摊分配的单次时间代价为 dd。

为了方便讨论,我们规定从 n=m/4n=m/4 开始,每次到下一次哈希表重建为止的所有插入操作将承担哈希表重建的代价。以第一次为例:

  • 目前 n=m/4n=m/4,再插入 m/4m/4 次就将触发哈希表重建;因此这 m/4m/4 次操作将承担重建的代价。

  • 重建哈希表所需的时间代价为 2mc2m c.

  • 求出被均摊分配的时间代价 d=2mcm/4=8cd=\frac{2mc}{m/4}=8c.

因此单次插入的均摊时间代价为 c+d=9cc+d=9c,O(9c)=O(1)O(9c)=O(1),仍然是常数级别。

Insight: Building & Egg Problem

nn 层楼,kk 个鸡蛋:求鸡蛋破碎的 critical height。典中典,但确实是一个好问题。

站在复杂度分析的角度,我们定义 T(n,k)T(n,k) 为 optimal # of probes in the worst case,即最坏情况下最优的时间;“最优”体现在存在一个最优的尝试位置,使得最坏时间尽量小。

base case:

  • k=1k=1 时,T(n,1)=nT(n,1)=n.
  • k>1k> 1 时,T(0,k)=0,T(1,k)=1T(0,k)=0, T(1,k)=1.
cpp
int T(int n, int k) {
    if (k == 1 || n == 0 || n == 1)  return n;
    if (t[n][k]) return t[n][k];
    
    int optimal_a = -1, minimal_cost = inf;
    for (int a = 1; a <= n; ++a) {
        int worstcase_cost = max(T(a - 1, k - 1), T(n - a, k)); // broken/not broken
        if (worstcase_cost < minimal_cost) {
            minimal_cost = worstcase_cost;
            optimal_a = a;
        }
    }
    pos[n][k] = optimal_a;
    return t[n][k] = minimal_cost + 1;
}

其中,每个 T(n,k)T(n,k) 所对应的 optimal_a 就是在该情况下鸡蛋尝试的 optimal position。

一般来说,根据不同的情况,我们采取不同的策略:

  • k=1k=1:别无选择,只能采用 linear search。Θ(n)\Theta(n)。
  • k>1k>1:由于有不止一个鸡蛋,可以采取 jump search 的策略;而其中最优的是 square-root search,即我们熟悉的分块策略。Θ(n)\Theta(\sqrt{n})。
  • k≥log⁡nk\geq \log{n}:此时鸡蛋的数量支持我们进行 binary search。Θ(log⁡n)\Theta(\log{n})。

以上的程序也能显示这一点。(issue: 并没有!准备去问一下 Hubert)

Radix Sort and Counting Sort

题目来自 2019 COMP2119 Final Exam Q4D(已解禁)。

Given an array of nn elements, where each element is an integer in {1,2,3,...,nk}\{1, 2, 3, ... , n^k\} for some small constant k≤2k\leq 2. The task is to sort the elements with asymptotic running time strictly better than O(nlog⁡n)O(n \log n). (You may use extra O(n)O(n) space.)

  • 条件 11: 优于 O(nlog⁡n)O(n\log{n}),考虑 counting sort。
  • 条件 22: Keys range from {1,2,3,...,nk}\{1,2,3,...,n^k\} 但仅有 O(n)O(n) extra space。考虑 counting sort 的进阶 - radix sort。

如何选取 radix?时刻记住,key range mm({1,2,3,..,m}\{1,2,3,..,m\}),radix kk 与 # of digits dd 满足关系:kd=mk^d=m,radix sort 的时间复杂度为 O(d(k+n))O(d(k+n))。

  • Key range mm 决定了键值数组的大小。
  • Radix kk 决定了桶数组的大小。
  • # of digits dd 决定了进行几轮 counting sort。

回到这道题,kk 已经保证了是一个 small enough constant,并且我们能使用的额外空间只有 O(n)O(n);(桶数组大小)这提示我们选取 nn 作为 radix。

  • Key range: nkn^k
  • Radix: nn
  • # of digits: log⁡nnk=k\log_n{n^k}=k

复杂度 O(k(n+n))=O(n)O(k(n+n))=O(n) since kk is small.

Binary Search Tree

关于 BST 一些容易忘记的小细节。

Successor

BST 中某节点的后继:

  • the minimum of TRT_R.
  • TRT_R 不存在:locate an ancestor aa that is a left child. the successor is aa's parent.
cpp
node* successor(node* x) {
    if (x->right != nullptr)
        return minimum(x->right);
    node* fa = x->parent;
    while ((fa != nullptr) && (x == y->right)) {
        x = fa;
        fa = fa->parent;
    }
    return fa;
}

前驱类似:

  • the maximum of TLT_L.
  • TLT_L 不存在:locate an ancestor aa that is a right child. the successor is aa's parent.

Deletion

删除节点 zz,分三种情况:

  • zz has no children: delete zz.
  • zz has one child: splice out zz.
  • zz has two children: replace zz by its immediate successor yy, and splice out yy (yy is the minimum of TRT_R for sure, which means it has at most one child)

定义 splice out 操作为将某点的 children 连到其 parent 上。splice out 只适用于删除只有一个孩子的节点。

cpp
void delete(root* T, node* z) {
    node* y;	// y is the node to be spliced out
    if ((z->left == NULL) || (z->right == NULL)) {
        y = z;
    } else {
        y = minimum(z->right);
        z->key = y->key;	// replace z by y, then delete y
    }
    // now splice out y, we can guarentee y has at most one child x
    node* x;
    if (y->left != nullptr)
        x = y->left;
    else
        x = y->right;
    
    // if y has no parent, we need to update root
    if (y->parent == nullptr)
        root = x;
    else {
        if (y->parent->left == y)
            y->parent->left = x;
        else
            y->parent->right = x;
    }
}

Tree Height Analysis

Complexity of insertion and deletion: O(h)O(h), and the best h=log⁡nh=\log{n}.

保证树高为 log⁡n\log{n} 的重要条件是插入 keys 的随机性,与保证快速排序效率需要 keys 随机性的原理相同。详情见 Algorithms, Princeton 课程的 quicksort 与 BST 部分。

朴素的删除会影响树的结构。在执行若干次删除操作后树会逐渐左倾。

Self-Balanced Tree: Height Analysis

题目来自 2019 COMP2119 Final Exam Q3C(已解禁)。

Suppose in a binary tree with n nodes, at every node, the difference of heights of the left and the right sub-tree is at most bb, where bb is some parameter that is at least 11. Prove that the height of the tree is at most O(blog⁡n)O(b\log n).

我们熟悉的 AVL 树就是 b=1b=1 的高度平衡树。

证明来自 MIT algorithm 6.006-spring-2014.

N(h)N(h), the minimum number of nodes in a tree with height hh, root rr. n=N(h)n=N(h). Without loss of generosity we express N(h)N(h) in terms of:

  • N(h−1)N(h-1), the minimum number of nodes in the left subtree of rr
  • N(h−b)N(h-b), the minimum number of nodes in the right subtree of rr
N(h)=1+N(h−1)+N(h−b) N(h)=1+N(h-1)+N(h-b)

Since N(h−1)>N(h−b)N(h-1)>N(h-b), we can say that

N(h)>1+N(h−b)+N(h−b)=1+2N(h−b)>2N(h−b) N(h)>1+N(h-b)+N(h-b)=1+2N(h-b)>2N(h-b)

Solve the recurrence N(h)>2N(h−b)N(h)>2N(h-b) and we get N(h)>2h/bN(h)>2^{h/b}

N(h)>2h/b  ⟺  log⁡N(h)>h/b  ⟺  h<blog⁡N(h)  ⟺  h=O(blog⁡n) N(h)>2^{h/b} \iff \log{N(h)}>h/b\iff h<b\log{N(h)}\iff h=O(b\log{n})

Proof completed.

Insight: Convert Linked List to BST

根据 sorted array 建 BST 很简单,这是因为它支持随机访问:O(n)O(n) 足矣。那 sorted linked list 又如何呢?

朴素算法:模仿 sorted array 的建立方法,在链表中暴力遍历到根的位置。满足 T(n)=2T(n/2)+O(n)T(n)=2T(n/2)+O(n),根据 master theorem 推出时间复杂度为 O(nlog⁡n)O(n\log{n})。

O(n)O(n) 算法:很巧妙。想象这样一个过程:给一颗完全二叉树,我们对其进行中序遍历,并将得到的值序列逐个写在链表中;以下算法就是上述过程的逆过程。

随着 head 指针在给定链表中迭代,我们还原出以该链表为中序遍历的一颗二叉树。该二叉树的结构又被二分放所保证,其高度一定是接近于 log⁡n\log{n} 的(其结构接近于完全二叉树)。

cpp
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};

TreeNode* sortedListToBST(ListNode* head) {
    if (head == nullptr)
        return nullptr;
    int len = 0;
    ListNode* curr = head;
    while (curr != nullptr) {
        ++len;
        curr = curr->next;
    }
    return buildBST(head, 0, len - 1);
}

TreeNode* buildBST(ListNode* head, int l, int r) {
    if (l > r)
        return nullptr;
    int mid = (l + r) / 2;
    TreeNode left = buildBST(head, l, mid - 1);
    TreeNode root = new TreeNode(head->val);
    root->left = left;
    head = head->next;
    root->right = buildBST(head, mid + 1, r);
    return root;
}

Bubble Sort: Average # of Swapping

一个小证明:冒泡排序平均会调用 swap() 函数多少次呢?

cpp
for (int i = n; i >= 2; --i) {
    for (int j = 1; j <= i - 1; ++j) {
        if (a[j] > a[j + 1])
            swap(a[j], a[j + 1]);
    }
}

对于长为 nn 的排列 SS(我们只关心排列,因为冒泡排序是 comparison-based sorting,基于元素间的大小关系而与具体数值无关),答案应当是 1n!∑I∈Sinv(I)\frac{1}{n!}\sum_{I\in S}\mathrm{inv}(I),其中 inv(I)\mathrm{inv}(I) 是排列 II 中的逆序对个数。

这个式子很难算。换个角度,考虑每一对逆序对对答案作出的贡献:选取两个数 a,b (a<b)a,b \ (a<b) 作为逆序对,再选取两个位置 i,j (i<j)i,j \ (i<j),将 bb 填入位置 ii,aa 填入位置 jj ,这样的逆序对共有 (Cn2)2(C_n^{2})^2 个。

每一个这样的逆序对会做出多少贡献?考虑一个逆序对 (b,a)(b,a),它们已经占据了 nn 个位置中的两个,那么这样的一个逆序对将会在 (n−2)!(n-2)! 个排列中出现;也就是,它们对答案的贡献是 (n−2)!(n-2)!。

那么长为 nn 的排列平均拥有的逆序对为 1n!(Cn2)2(n−2)!=n(n−1)4\frac{1}{n!}(C_n^2)^2(n-2)!=\frac{n(n-1)}{4}。这就意味着冒泡排序将对长为 nn 的数组(假设元素 distinct)调用平均 n(n−1)4\frac{n(n-1)}{4} 次 swap() 函数。

Heap: Linear Heap Building

众所周知,堆有两种建法:

  • 向空堆中插入 nn 次,复杂度 O(nlog⁡n)O(n\log{n})
  • heapify 方法,复杂度 O(n)O(n)

这里主要讲下线性建堆方法的复杂度证明(以大根堆为例)。

cpp
void sink(int x) {
    while (x * 2 <= n) {
        int child = x * 2;
        if (child + 1 <= n && a[child + 1] >= a[child])
            ++child;          // right child > left child
        if (a[child] <= a[x])
            break;            // heap property is not violated
        swap(a[child], a[x]);
        x = child;
    }
}

void heapify() {
    for (int i = n; i >= 1; --i)	sink(i);
}

若堆高为 hh,则高度为 ii 的节点最多需要被 swap h−ih-i 次。由于堆是二叉树,高度为 ii 的节点最多有 2i2^i 个。

因此总 swap 次数为:

T(n)=∑i=1h2i(h−i)=∑i=1hi2h−i=2h∑i=1hi2i T(n)=\sum_{i=1}^h 2^i(h-i)=\sum_{i=1}^h i2^{h-i}=2^h\sum_{i=1}^h\frac{i}{2^i}

令 x=12x=\frac{1}{2},则 L=∑ii2iL=\sum_i\frac{i}{2^i}。我们有:

①:L=x+2x2+3x3+...②:xL=0+x2+2x3+...①−②:(1−x)L=x+x2+x3+...=x(1+x+x2+...)=x1−x \begin{aligned} ①&:L=x+2x^2+3x^3+... \\ ②&:xL=0+x^2+2x^3+... \\ ①-②&:(1-x)L=x+x^2+x^3+...=x(1+x+x^2+...)=\frac{x}{1-x}\\ \end{aligned}

解得 L=x/(1−x)2=2L=x/(1-x)^2=2。所以 O(T(n))=O(2hL)=O(2h)=O(n)O(T(n))=O(2^hL)=O(2^h)=O(n).

Randomized Quicksort Analysis

众所周知,快排在序列 already sorted 或 reverse-sorted 时有最坏时间复杂度 O(n2)O(n^2),随机化使得这种情况出现的概率可以忽略不计。但是随机化快排的时间复杂度又怎么分析呢?

当然是取平均!由于随机化,partition 产生的两个子序列的长度可能是 (0,n−1)(0,n-1), (1,n−2)(1,n-2) ... (n−1,0)(n-1,0) 共 nn 种情况,且概率相等,均为 1n\frac{1}{n}。那么对长度为 nn 的序列排序所需的时间 T(n)T(n) 为:

T(n)=2n∑i=0n−1T(i)+cn T(n)=\frac{2}{n}\sum_{i=0}^{n-1} T(i)+cn

接下来我们要证明的是 T(n)≤Anlog⁡nT(n)\leq An\log{n},其中 AA 是某个常数。采用 induction method:

  • base case
    • T(0)=0,T(1)=1T(0)=0,T(1)=1
    • T(2)=1+2c≤Alog⁡2T(2)=1+2c\leq A\log2(提示我们 AA 应该是一个 large enough constant)
  • induction hypothesis: assume for 2≤i≤n−12\leq i \leq n-1, T(i)≤Ailog⁡iT(i)\leq Ai\log{i}

进行 induction:

T(n)=2n∑i=0n−1T(i)+cn≤2n⋅∑i=0n−1Ailog⁡i+cn≤2nAn(n−1)2log⁡n+cn=Anlog⁡n−Alog⁡n+cn \begin{aligned} T(n)&=\frac{2}{n}\sum_{i=0}^{n-1}T(i)+cn \\ &\leq \frac{2}{n}\cdot \sum_{i=0}^{n-1}Ai\log{i}+cn\\ &\leq \frac{2}{n}A \frac{n(n-1)}{2}\log{n}+cn \\ &=An\log{n}-A\log{n}+cn \end{aligned}

可以发现还是没法证明 T(n)≤Anlog⁡nT(n)\leq An\log{n}。重点在于常数 AA 的选取上。

我们尝试进行更加细致的放缩。由于

ilog⁡i≤{ilog⁡n2,  i=2,...,n2ilog⁡n,  i=n2+1,...,n i\log{i}\leq\left\{ \begin{matrix} \begin{aligned} i\log{\frac{n}{2}}, \ \ i&=2,...,\frac{n}{2} \\ i\log{n}, \ \ i&=\frac{n}{2}+1,...,n \end{aligned} \end{matrix} \right.

我们有

T(i)≤{A(ilog⁡n−i),  i=2,...,n2Ailog⁡n,  i=n2+1,...,n T(i)\leq\left\{ \begin{matrix} \begin{aligned} A(i\log{n}-i), \ \ i&=2,...,\frac{n}{2} \\ Ai\log{n}, \ \ i&=\frac{n}{2}+1,...,n \end{aligned} \end{matrix} \right.

通过对 ii 分类讨论,引入了新的一项 −Ai-Ai。我们用这个更加准确的式子进行放缩。

T(n)=2n∑i=0n−1T(i)+cn≤2nA⋅(∑i=0n−1ilog⁡i−∑i=0n−1i)+cn≤Anlog⁡n−Alog⁡n−2nA⋅12(n2)(n2+1)+cn=Anlog⁡n−Alog⁡n−A2(n2+1)+cn \begin{aligned} T(n)&=\frac{2}{n}\sum_{i=0}^{n-1}T(i)+cn \\ &\leq \frac{2}{n}A\cdot (\sum_{i=0}^{n-1}i\log{i}-\sum_{i=0}^{n-1}i)+cn\\ &\leq An\log{n}-A\log{n}-\frac{2}{n}A\cdot\frac{1}{2}(\frac{n}{2})(\frac{n}{2}+1) +cn\\ &= An\log{n}-A\log{n}-\frac{A}{2}(\frac{n}{2}+1)+cn \end{aligned}

为证明 T(n)≤Anlog⁡nT(n)\leq An\log{n},我们选取常数 AA 使得其能抵消 cncn 带来的影响。令 cn≤A2(n2+1)cn\leq \frac{A}{2}(\frac{n}{2}+1),发现取 A=4cA=4c 能够满足要求。因此 T(n)T(n) 的上界得证:T(n)≤Anlog⁡n=4cnlog⁡n=O(nlog⁡n)T(n)\leq An\log{n}=4cn\log{n}=O(n\log{n})

Huffman Tree: Key lemma

Key lemma of Huffman tree.

Given a tree TT, we can find a tree T′T', with the two minimum cost leaves as siblings, and C(T′)≤C(T)C(T')\leq C(T).

C(T)C(T) 是 TT 的 total weighted path length(WPL)。给出一颗树 TT,不断对其应用 key lemma,其总 WPL 会持续减小。最小 WPL 对应的是 optimal prefix tree, 即 Huffman tree。

CC BY-NC-SA 4.0
正在加载评论…