免費詳解 / 交大 / 軟體 / 102

102 交大資工所考古題解答|軟體逐題詳解

102 交大資工所軟體考古題的逐題詳解,共 18 題,免費公開。

逐題詳解

15%

In the Knuth-Morris-Pratt string-pattern matching algorithm, we need a failure function. Compute the failure function for the following pattern.

index012345678
patternabaabaaaa
failure

failure\((j)\) = 最大的 \(i\lt j\) 使 \(p[0..i]=p[j-i..j]\)(沒有就是 \(-1\))

index012345678
patternabaabaaaa
failure−1−10012300

\(j=3\):abaa 的最長 border 是 a → \(i=0\)

\(j=6\):abaabaa 的 border 是 abaa(長度 4) → \(i=3\)

\(j=7\):abaabaaa 只剩 a 可當 border → 0

\(-1,\ -1,\ 0,\ 0,\ 1,\ 2,\ 3,\ 0,\ 0\)

25%

In a binary tree, there may be many null pointers. We may use these pointers to point to in-order predecessors and successors. These pointers are called thread pointers. Draw all the thread pointers in the following binary tree.

(Figure 2:A 是 root,只有左子 B;B 的左子 E、右子 C;E 的左子 K、右子 F;K 的右子 L;C 的左子 G、右子 D;D 的左子 H;H 的左子 M、右子 I;I 的右子 J。節點不分左右畫在題目圖上,以上是依圖還原)

in-order:K L E F B G C M H I J D A

左指標是 null → 指向 in-order predecessor;右指標是 null → 指向 in-order successor;第一個與最後一個接到 head node

node左 thread →右 thread →
Khead(有右子 L)
LKE
FEB
GBC
MCH
IH(有右子 J)
JID
D(有左子 H)A
A(有左子 B)head

headKLEFBGCMHIJDA藍:左 thread(→ in-order predecessor)紅:右 thread(→ in-order successor)

13 個節點共 26 個 pointer,12 條是真的邊,其餘 14 個 null 都變成 thread(左 7 條、右 7 條)

如圖:共 14 條 thread

35%

Assume there are only variables such as a, b, c, … and binary operators, such as +, −, *, and / in an arithmetic expression. The expression is fully parenthesized, that is, there is a pair of parentheses for each operator. Examples are (((a+b)−c)/d), ((a+(c−(b−a)))/d)+f), ((((a+b)+c)+d)+e), etc.

Write a program that translated a fully-parenthesized expression into its prefix form. The input is a correct, fully-parenthesized arithmetic expression, stored in a read-only array. This program can use 3 queues together with the usual stack pointers. You cannot use additional storage, such as arrays, except a fixed number of simple temporary variables. In the program, you can only push, pop, examine the contents of a cell, and compare two contents of two cells for equality. The program can scan the input from left to right only once. It cannot store the input expression somewhere else for repeated examinations. You can use C or Java or Pascal or other similar programming languages to write this program. Your program should clearly show the underlying algorithm. Minor details and errors in the program will be tolerated. In particular you need to explain your data structures with examples.

三個陣列各配一個 stack pointer,只用 push/pop/比較:\(D\)(主 stack)、\(Q_2\)、\(Q_3\)(只在合併時暫存,用完清空)

\(D\) 裡存「已經完成的 prefix 片段」,每個片段前面壓一個記號 #,片段內是 prefix 順序(底→頂);運算子在左右片段之間先暫放

for each token t of the input (left to right, once):
    if t == '(' :  skip
    if t is a variable:  push(D,'#'); push(D,t)
    if t is an operator: push(D,t)
    if t == ')':
        while ((c = pop(D)) != '#')  push(Q2, c)     // 右運算元 R(倒著出來)
        op = pop(D)                                   // 一個暫存變數
        while ((c = pop(D)) != '#')  push(Q3, c)     // 左運算元 L(倒著出來)
        push(D,'#'); push(D,op)
        while (Q3 not empty)  push(D, pop(Q3))       // 再倒一次 → L 回到原順序
        while (Q2 not empty)  push(D, pop(Q2))       // 再倒一次 → R 回到原順序
// 結束:D = '#' 接整個 prefix,由底往頂讀(只讀 cell)就是答案

pop 進 \(Q_2,Q_3\) 會把片段倒過來,再 pop 回 \(D\) 又倒回正序,所以 \(op\ L\ R\) 可以直接疊回 \(D\)

範例 ((a+b)*c)(\(D\) 由底到頂):

讀到動作\(D\)\(Q_2\)\(Q_3\)
( (略過
apush # a# a
+push +# a +
bpush # b# a + # b
)R=b,op=+,L=a,重組# + a b
*push *# + a b *
cpush # c# + a b * # c
)R=c,op=*,L=+ab,重組# * + a b c

prefix = *+abc

每個字元至多被搬 \(O(\text{深度})\) 次,總共 \(O(n^2)\) 次 push/pop;再試 ((a+(c-(b-a)))/d) 得 /+a-c-bad

45%

Assume each node contains a data, lthread, rthread, lchild, and rchild fields. lthread and rthread are Boolean fields. lchild and rchild are pointers. If lthread is true, the lchild field will be considered as a left thread; otherwise, lchild will point to the left child. Similarly for the rthread and rchild fields. Consider the following algorithm for pre-order traversal of a binary tree using thread pointers:

1.  presucc(node) {
2.      if node→lthread = false
3.          then return node→lchild;   /* has left child */
4.      if node→rthread = false
5.          then return node→rchild;   /* has right child */
6.      ______________   /* in-order successor */
7.      /* find the in-order successor of the in-order successor of the node's in-order successor */
8.      while node→rthread = true do
9.          node := node→rchild;
10.     return node→rchild;
11. }

Please fill in the missing line 6 with an assignment statement.

第 2–5 行之後,node 是 leaf(左右都是 thread)

leaf 的 rchild 這個 thread 指到它的 in-order successor \(s\),這個點的左子樹含 node

preorder 的下一個是 \(s\) 的右子(\(s\) 沒有右子,就沿著 thread 往上找到有右子的點 \(s'\),回傳 \(s'\)→rchild)

第 8–10 行就是這個「沿 thread 往上找」,所以第 6 行要先把 node 移到 in-order successor

node := node→rchild;

55%

This problem contains five yes-no questions. Each question counts as 1 point. You do not need to explain your answers.

(a) \(n^{2n}+5\cdot3^{2n}=\Theta(n^{2n})\). (b) \(3n^{1.0001}+99n\log n=O(n^{1.1})\). (c) \(n\log(2n)=O(n\ln n)\). (d) \(n^2\log(5n)=\Theta(n^2)\). (e) \(n^{0.999}\log n=\Theta(n^2)\).

(a) \(3^{2n}=9^n\),\(n^{2n}=(n^2)^n\),\(n\ge4\) 時 \(n^2\gt9\),第一項勝出 → Yes

(b) \(n\log n=o(n^{1.0001})\),整個是 \(\Theta(n^{1.0001})\),指數 \(1.0001\lt1.1\) → Yes

(c) \(\log(2n)=1+\log n=\Theta(\ln n)\) → Yes

(d) \(\log(5n)\to\infty\),\(n^2\log(5n)\) 不被 \(c\,n^2\) 壓住 → No

(e) \(n^{0.999}\log n=o(n)\),連 \(\Omega(n^2)\) 都不成立 → No

(a) Yes (b) Yes (c) Yes (d) No (e) No

65%

You have the following data structures A. list, B. hash table, and C. AVL tree at your disposal. Assume you have a lot of data in the form of key-value pairs ⟨key1, value1⟩, ⟨key2, value2⟩, …, ⟨keyN, valueN⟩. Please answer the following questions by making your choices from the three data structures:

(1) If your application requires frequent random access (i.e. retrieving the value for a given key), using the data structure ____ to store the data will give the longest average access time.

(2) Assume there is a total ordering of data, and your application requires frequent range queries to the data (i.e. retrieving data with keys in the range [lower_bound, upper_bound]). Range query to your data can be efficiently implemented with the data structure ____.

(3) If we want to emulate a priority queue, which of the three data structures will be the best choice (i.e. both element addition and extract-max have to be efficient) ____.

(1) list 依 key 找要掃過去,平均 \(O(n)\);hash \(O(1)\)、AVL \(O(\log n)\) → A

(2) AVL:\(O(\log n)\) 找到 lower_bound,再 in-order 往後走 \(k\) 筆;hash 把 key 打散,做不到範圍

(3) insert 與 extract-max 在 AVL 都是 \(O(\log n)\),max 在最右端;list 要 \(O(n)\)(或 insert 或 extract),hash 找不到 max

(1) A (2) C (3) C

75%

Figure 4 shows the two tree rotation operations commonly used for balancing binary search trees.

right_rotate(Q):Q 的左子 P 上來,P 的右子 B 變成 Q 的左子(Q 在 P 右邊);left_rotate(P):P 的右子 Q 上來,Q 的左子 B 變成 P 的右子。

Given the binary search tree T in Figure 5 (root 4;2 的子是 1、3;6 的子是 5、7), let's apply the following tree rotations in sequence on T: left_rotate(6) → right_rotate(4) → left_rotate(4)

(1) After the tree rotations, the parent of node 4 will be node ____.

(2) After the tree rotations, the parent of node 7 will be node ____.

Let's apply the following additional tree rotations in sequence: left_rotate(1) → right_rotate(4) → left_rotate(6) → right_rotate(3).

(3) After the seven tree rotations are applied to T, an in-order traversal of T will output a sequence of the tree nodes as ____.

1234567
T
1234567
left_rotate(6)
1234567
right_rotate(4)
1234567
left_rotate(4)

left_rotate(6):6 的右子 7 上來 → 7 的左子(空)變 6 的右子

right_rotate(4):4 的左子 2 上來,2 的右子 3 變 4 的左子

left_rotate(4):4 的右子 7 上來,7 的左子 6 變 4 的右子

(1) 7 (2) 2

後四次:left_rotate(1)(1 沒有右子,不動)→ right_rotate(4)(4 的左子 3 上來)→ left_rotate(6)(6 沒有右子,不動)→ right_rotate(3)(3 沒有左子,不動)

1234567
七次之後

旋轉不改變 in-order,結果一定是排序後的序列

(3) 1 2 3 4 5 6 7

85%

We have an open addressing hash table of size 7 to store integer keys, with hash function \(h(x)=x\bmod7\). Assume we use linear probing for collision resolution and insert elements in the order 1, 15, 14, 3, 9, 5, 27.

(1) Draw the hash table after the insertions (2) What is the worst-case time complexity for searching in a hash table of size \(N\) (3) What is the best-case time complexity for searching in a hash table of size \(N\)

1 → 1;15 → 1 已佔,放 2;14 → 0;3 → 3;9 → 2 已佔、3 已佔,放 4;5 → 5;27 → 6

slot0123456
key1411539527

(2) 所有 key 都擠在同一串 probe,要走完 → \(O(N)\)

(3) 第一次就命中 → \(O(1)\)

(1) 如表 (2) \(O(N)\) (3) \(O(1)\)

95%

Figure 6 presents the code for sorting an integer array. Assume that we make a call to the xsort(…) function with

void swap(int &v1, int &v2) { int t; t = v2; v2 = v1; v1 = t; }
void partition(int data[], int size, int pivot_v, int& low, int& high) {
    low = -1;
    high = size;
    for (int i = 0; i < high;) {
        if (data[i] > pivot_v) {
            swap(data[i], data[++low]);
            ++i;
        } else if (data[i] < pivot_v) {
            swap(data[i], data[--high]);
        } else {
            ++i;
        }
    }
}
void xsort(int data[], int size)
{
    int pivot, low, high;
    if (size <= 1)
        return;
    pivot = size/2;
    partition(data, size, data[pivot], low, high);
    xsort(data, low+1);
    xsort(data+high, size - high);
}

int data[] = {2,0,1,3,2,4,1,0,0,1}; int size = 10;

(1) After the call to xsort returns, the content of the data[] array will be ____ (list all 10 elements sequentially).

(2) How many times will the function partition be invoked? ____ times.

(3) The worst-case time complexity of the xsort function for an input array data[] with size elements is ____.

partition:大於 pivot 的往前丟、小於 pivot 的往後丟、等於 pivot 的留在中間 → 大到小的 3-way quicksort(Dutch national flag)

\([0,\text{low}]\) 是大於 pivot 的,\([\text{high},\text{size})\) 是小於 pivot 的,中間是等於 pivot;遞迴只處理兩邊

次sizepivot 值lowhighpartition 後的 data
1104-114 1 3 2 0 1 0 0 1 2
291264 3 2 2 1 1 1 0 0 0
332034 3 2 2 1 1 1 0 0 0
430-134 3 2 2 1 1 1 0 0 0

第 1 次 pivot 取到最大值 4,左邊 size 0 不用遞迴,右邊剩 9 個;之後的遞迴只有 size 3 的兩塊 \([3,2,2]\)、\([0,0,0]\) 還要 partition(size ≤ 1 的直接 return)

(1) 4 3 2 2 1 1 1 0 0 0 (2) 4 次

(3) 每次 pivot 取到極端值(例如已排序的陣列,pivot=size/2 是中位數看不出來,但 pivot 總是最大值或最小值的輸入存在),\(T(n)=T(n-1)+O(n)\)

\(O(n^2)\)

105%

Figure 7 presents the code for computing the number of connected components in an undirected graph. In the code, the undirected graph is stored in the form of adjacency lists. The graph has N vertices, which correspond to vertices[N] at Line 25. Each vertex is a tVertex structure as given at Line 9~20. The function ConnectUndirected(v1, v2) is used for creating an undirected edge between vertex v1 and vertex v2. The function NumberOfComponents() at Line 36 will return the number of connected components in the graph. Please complete the code by filling the blanks in Figure 7. There are a total of three blanks at Line 30, 32, and 43 to be filled.

25  tVertex vertices[N];
27  void DFS (int v)
28  {
29      tListNode *pN;
30      vertices[v].visited = ____________;
32      for ( pN = vertices[v].pAdjList; pN ; ______________ )
33          if ( !vertices[pN->v].visited ) {  DFS( pN->v); }
34  }
36  int NumberOfComponents ()
37  {
38      int k;
39      int cnt = 0;
41      for ( k = 0; k < N; k++)   vertices[k].visited = false;
42      for ( k = 0; k < N; k++) {
43          if ( !vertices[k].visited ) { ____________ }
44      }
45      return cnt;
46  }

DFS 進到 v 先標記,再沿 adjacency list 走訪

Line 30:true

Line 32:for 迴圈的更新項,走到 list 的下一個節點

Line 32:pN = pN->pNext

Line 43:還沒被走過的點是新 component 的起點,一次 DFS 會把整個 component 標記完,計數加一

Line 43:DFS(k); cnt++;

115%

Suppose that the amount of flow in the maximum flow from source to sink in the network \(G=(V,E)\) is \(f\), and that all capacities are integral. Suppose \(n=|V|\) and \(m=|E|\). How long would it take at most to find this maximum flow using the Ford-Fulkerson algorithm? ____. Suppose that the minimum s-t cut in the network \(G\) has \(x\) arcs. Suppose that one adds \(y\) units of capacity to each arc of \(G\), creating a transformed network \(G'\). The capacity of the minimum cut of \(G'\) is at most ____.

每輪找 augmenting path(BFS/DFS)\(O(m)\);capacity 都是整數,每輪流量至少加 1,至多 \(f\) 輪

\(O(mf)\)

原本的 min cut(容量 \(f\),\(x\) 條 arc)在 \(G'\) 中每條多 \(y\),容量變成 \(f+xy\);\(G'\) 的 min cut 不會比這個 cut 還大

\(f+xy\)

125%

The running time of Kruskal's algorithm for a connected undirected weighted graph \(G=(V,E)\) is ____. Suppose that all edge weights in a graph \(G\) are integers in the range from 1 to \(|V|\). How fast can you make Kruskal's algorithm run? ____

排序 \(E\) 條邊 \(O(E\log E)\),加上 union-find;\(E\le V^2\) → \(\log E=O(\log V)\)

\(O(E\log V)\)

權重是 \(1..|V|\) 的整數 → counting sort \(O(V+E)\),連通圖 \(E\ge V-1\),排序降到 \(O(E)\);剩下 \(E\) 次 find/union

\(O(E\,\alpha(V))\)

135%

If some of the edge weights in a graph are negative, the shortest path can be obtained using Dijkstra's algorithm by first adding a large constant \(C\) to each edge weight, where \(C\) is large enough that every resulting edge weight will be nonnegative (True or False). ____ The Bellman-Ford algorithm is not suitable if the input graph has negative-weight edges (True or False). ____

(1) 每條邊加同一個 \(C\),邊數多的路徑被多罰幾個 \(C\);原本最短的路徑(邊數多)加完不一定還是最短 → F

例:\(s\to a\to b\to t\) 權重 \(1,1,-3\)(總 \(-1\))對 \(s\to t\) 權重 0;加 \(C=3\) 後前者 \(4+4+0=8\)、後者 3

(2) Bellman-Ford 本來就是為負權邊設計的,只有碰到 negative cycle 才失效 → F

(1) False (2) False

145%

Given a graph as below. Show the weight on the edge between Node \(x\) and Node \(y\) after reweighting using Johnson's algorithm. ____ Show the fifth row of an adjacent matrix (with order of \(u,v,x,y,z\)) after using the Floyd-Warshall Shortest Paths algorithm with the intermediate Node \(u\). ____

uvzxy5-28-4397267

(圖:\(u\to v\) 5、\(v\to u\) −2、\(u\to x\) 8、\(u\to y\) −4、\(z\to u\) 6、\(z\to x\) 7、\(x\to v\) 3、\(x\to y\) 9、\(y\to v\) 7、\(y\to z\) 2)

Johnson:加 source \(s\),對每個點連 0 的邊,Bellman-Ford 求 \(h(\cdot)\)

點uvxyz
\(h\)−200−6−4

\(h(y)=h(u)+w(u,y)=-2-4=-6\);\(h(z)=h(y)+w(y,z)=-6+2=-4\);\(h(u)=\min(0,\,h(v)-2,\,h(z)+6)=-2\)

\(\hat w(x,y)=w(x,y)+h(x)-h(y)=9+0-(-6)=15\)

15

Floyd-Warshall,只放 \(u\) 當 intermediate:\(d(i,j)=\min\{w(i,j),\ w(i,u)+w(u,j)\}\)

第 5 列是 \(z\):\(z\to u=6\);\(z\to v=6+5=11\);\(z\to x=\min(7,\,6+8)=7\);\(z\to y=6+(-4)=2\);\(z\to z=0\)

\((6,\ 11,\ 7,\ 2,\ 0)\)

155%

You are the program chair of a conference! Part of your job is to assign papers to reviewers. You have 6 papers P1, P2, P3, P4, P5, P6 and 3 reviewers R1, R2, R3. Initially, each reviewer constructs a list of papers he is willing to review as followings: R1 = {P1, P3, P5, P6}, R2 = {P1, P2, P4}, R3 = {P1, P2, P3, P4, P5, P6}. An assignment of papers to reviewers is valid if each paper is assigned to at least 2 distinct reviewers that are willing to review that paper. The maximum number of papers assigned to any one reviewer should not be greater than 4. You would like to maximize the total number of papers which are validly assigned. Please model this problem using a s-t flow network \(G=(V,E)\) (Draw a flow network with capacity labeling). ____ What is the maximum number of papers that can be validly assigned? ____

建模:\(s\to R_i\) 容量 4(每位審稿人至多 4 篇);\(R_i\to P_j\) 容量 1(\(R_i\) 願意審 \(P_j\) 才連);\(P_j\to t\) 容量 2(一篇要湊滿兩位不同審稿人)

sR1R2R3P1P2P3P4P5P6t444222222

(圖中 \(R_i\to P_j\) 的邊容量都是 1;紅色是下面求出的一組最佳指派)

一篇 paper 的 \(P_j\to t\) 被灌滿 2 單位,就是有效指派

最大篇數:除了 P1 以外,P2–P6 每篇願意審的人都只有兩位、而且都包含 R3(P2、P4:R2+R3;P3、P5、P6:R1+R3)

這五篇要有效,R3 都必須審;R3 至多 4 篇 → P2–P6 最多 4 篇有效;P1 靠 R1+R2 即可 → 最多 \(4+1=5\)

達到 5:P1(R1、R2)、P2(R2、R3)、P4(R2、R3)、P3(R1、R3)、P5(R1、R3) → R1:3 篇、R2:3 篇、R3:4 篇

5 篇

165%

Consider the multiplication of four matrices with dimensions in the following order: 10×11, 11×25, 25×40, 40×2. Find the optimal parenthesization of the above product and the minimum number of scalar multiplications needed.

\(p=\langle10,11,25,40,2\rangle\),\(m[i,j]=\min_k\,m[i,k]+m[k+1,j]+p_{i-1}p_kp_j\)

\(m[i,j]\)\(A_2\)\(A_3\)\(A_4\)
\(A_1\)2750127502770(\(k=1\))
\(A_2\)110002550(\(k=2\))
\(A_3\)2000

\(m[1,4]\) 三個候選:\(k=1\):\(0+2550+10\cdot11\cdot2=2770\);\(k=2\):\(2750+2000+10\cdot25\cdot2=5250\);\(k=3\):\(12750+0+10\cdot40\cdot2=13550\)

\(m[2,4]\):\(k=2\):\(0+2000+11\cdot25\cdot2=2550\);\(k=3\):\(11000+0+11\cdot40\cdot2=11880\)

\((A_1(A_2(A_3A_4)))\),最少 2770 次純量乘法

175%

Consider the problem of finding a vector \((x_1,x_2,x_3,x_4,x_5)\) satisfying the following constraints such that \(x_1+x_2+x_3+x_4+x_5\) is maximized, where \(x_i\le0\) for \(i=1,\ldots,5\). What are the maximum value and the corresponding vector?

\(x_1-x_2\le1,\ x_1-x_5\le-1,\ x_2-x_5\le1,\ x_3-x_1\le15,\ x_4-x_1\le4,\ x_4-x_3\le-1,\ x_5-x_3\le-3,\ x_5-x_4\le0.\)

difference constraints:\(x_i-x_j\le c\) 看成 \(x_j\to x_i\) 權重 \(c\) 的邊;再加 source \(s\) 對每個點連 0 的邊(\(x_i\le0\))

每個 \(x_i\) 的上界就是 \(s\) 到它的最短路徑長,同時取到上界得到的向量滿足所有限制,且每個分量最大,總和最大

邊:\(x_2\to x_1\):1;\(x_5\to x_1\):−1;\(x_5\to x_2\):1;\(x_1\to x_3\):15;\(x_1\to x_4\):4;\(x_3\to x_4\):−1;\(x_3\to x_5\):−3;\(x_4\to x_5\):0

沒有 negative cycle;\(s\to x_3\):0,\(x_3\to x_5\):−3,\(x_5\to x_1\):−1 → \(x_1=-4\)

\(x_5=-3\);\(x_4=\min(0,\ x_3-1)=-1\),\(x_4\to x_5\):\(-1+0\gt-3\),\(x_5\) 仍是 −3;\(x_2=\min(0,\ x_5+1=-2)=-2\);\(x_1=\min(0,\ x_2+1,\ x_5-1)=-4\)

\(x_1\)\(x_2\)\(x_3\)\(x_4\)\(x_5\)
最短路徑長−4−20−1−3

最大值 \(-10\),向量 \((-4,\,-2,\,0,\,-1,\,-3)\)

1815%

Consider a set of 6 nodes 1, 2, 3, 4, 5, 6 and their corresponding weights: 2, 3, 4, 4, 5, 6.

(a) (5%) Build a binary tree with these nodes appearing in the leaves such that the maximum of \(w[i]\times(1/2)^{d[i]}\) is minimized, where \(w[i]\) is the weight and \(d[i]\) is the depth of node \(i\) in the tree. Note that the root has depth 0. What is the optimal value?

(b) (10%) Give a greedy algorithm for \(N\) nodes and explain your idea.

(a) binary tree 的每個內部節點有兩個子節點(full binary tree) → leaf 深度滿足 \(\sum_i2^{-d_i}=1\)

目標 \(\max_i w_i2^{-d_i}\le M\) ⇔ 每個 leaf \(2^{-d_i}\le M/w_i\),\(2^{-d_i}\) 取不超過 \(M/w_i\) 的最大 2 的冪,這些上限加起來要 \(\ge1\) 才湊得出 1

\(M=\tfrac58\):權重 \(2,3,4,4,5,6\) 的上限依序是 \(\tfrac14,\tfrac18,\tfrac18,\tfrac18,\tfrac18,\tfrac1{16}\),總和 \(\tfrac{13}{16}\lt1\) → 不行;\(M\) 介於 \(\tfrac58\) 與 \(\tfrac34\) 之間時上限都不變(權重 6 的上限是 \(\tfrac1{16}\),要 \(M\ge\tfrac68\) 才變 \(\tfrac18\))

\(M=\tfrac34\):上限 \(\tfrac14,\tfrac14,\tfrac18,\tfrac18,\tfrac18,\tfrac18\),總和 \(=1\) → depth \((2,2,3,3,3,3)\) 做得到

weight234456
depth223333
\(w\cdot2^{-d}\)1/23/41/21/25/83/4

3•6•5•2•4•4

最佳值 \(\tfrac34\)

(b) 兩個 leaf \(a,b\) 在深度 \(d\) 當兄弟時,貢獻是 \(\max(a,b)\cdot2^{-d}=\dfrac{\max(a,b)}{2}\cdot2^{-(d-1)}\)

所以可以把這對兄弟換成「一個 weight 為 \(\max(a,b)/2\)、深度少 1 的 leaf」,節點少 1、目標值不變。最深的一對兄弟配最大的兩個 weight 最划算(交換論證:大 weight 放淺處不會更好)

把 N 個 weight 放進 max-heap
repeat N-1 次:
    a = extract-max;  b = extract-max
    把 max(a,b)/2 = a/2 做成內部節點(左右子 = a、b 對應的子樹)insert 回 heap
heap 剩下的值就是最佳的 max w·2^(-d);追蹤各次合併就得到樹

每次 \(O(\log N)\),共 \(O(N\log N)\)

套在 (a):\(\{6,5\}\to3\)、\(\{4,4\}\to2\)、\(\{3,3\}\to1.5\)、\(\{2,2\}\to1\)、\(\{1.5,1\}\to0.75\)

greedy:每次合併目前最大的兩個 weight,新 weight = 較大者的一半

109–115 的詳解也是這樣寫的。

國立陽明交通大學 109–115 的詳解收錄在付費版;106–115 全年度完整詳解共 579 頁,逐題推導。

購買 · NT$ 850 看交大其他免費詳解

其他年度與考科

同一年的其他科

同一科的其他年度

聯絡我們

題目有錯、詳解看不懂,都歡迎來信

想許願補哪一份、對購買有疑問也可以,收到後會盡快回覆。

william.chou.123123@gmail.com