免費詳解 / 師大 / 軟體 / 103

103 師大資工所考古題解答|軟體逐題詳解

103 師大資工所軟體考古題的逐題詳解,共 9 題,免費公開。

逐題詳解

110 分

Please show an example of worse case for the Quicksort such that the Quicksort cannot finish in \(O(N\log N)\) time complexity.

pivot 取第一個元素(或最後一個),輸入已經排好:\(1,2,3,4,5,\dots,N\)

例 \(N=5\):\([1,2,3,4,5]\),pivot = 1,比 1 小的 0 個、比 1 大的 4 個 → 切成 \(\varnothing\) 與 \([2,3,4,5]\)

\([2,3,4,5]\),pivot = 2 → \(\varnothing\) 與 \([3,4,5]\) ……每次只少 1 個元素,遞迴深度 \(N-1\)

每一層 partition 要比較 \(n-1,\ n-2,\dots,1\) 次,總共 \((N-1)+(N-2)+\cdots+1=\dfrac{N(N-1)}2\)

遞迴式 \(T(N)=T(N-1)+O(N)\)

反排序 \(N,N-1,\dots,1\)(pivot 取第一個)、全部元素相同(用 ≤ 分割)也是同樣情形;pivot 取 median 或隨機可避開這種輸入

已排序的輸入 → \(O(N^2)\)

25 分

Please show the Max Heap (binary tree) after we insert 4, 2, 6, 1, 5, 7, 3 sequentially.

每次插在最後一個位置,與父節點比,比父節點大就交換往上

4插 442插 2624插 6:與 4 交換6241插 165412插 5:與 2 交換756124插 7:與 4、6 交換7561243插 3:完成

\([7,5,6,1,2,4,3]\):根 7,左子 5(子 1、2),右子 6(子 4、3)

35 分

Continued from the previous question. Please show the Max Heap (binary tree) after we delete an element from the root of the heap.

刪根:把最後一個元素 3 搬到根,heap 大小減 1,再往下與較大的子節點交換

7561243原 heap356124最後一個 3 搬到根653124與較大子 6 交換654123與子 4 交換:完成

\([6,5,4,1,2,3]\):根 6,左子 5(子 1、2),右子 4(左子 3)

410 分

Please write the pseudocode that deletes a node (pointed by pCurrent) from the following double linked list, and then sets pCurrent to the next node.

pCurrent → [data | next | previous] ⇄ [data | next | previous] ⇄ [data | next | previous] ⇄ [data | next | previous](pCurrent 指向左邊數來第二個節點)

deleteNode(pCurrent):
  if pCurrent == NULL: return
  p = pCurrent
  if p->previous != NULL:
      p->previous->next = p->next      // 前一個節點跳過 p
  else:
      head = p->next                    // p 是第一個節點
  if p->next != NULL:
      p->next->previous = p->previous  // 後一個節點接回前一個
  pCurrent = p->next                    // pCurrent 移到下一個節點
  free(p)

圖中的 pCurrent 在第二個節點,前後都有節點,兩個指標都要改;p 在尾端時 p->next 為 NULL,pCurrent 變成 NULL。free 之前先把 p->next 存起來,不能在 free 之後再讀

520 分

A sparse matrix is a matrix that contains many zero entries. The following shows an example: \(\begin{bmatrix}15&0&0&22&0\\0&11&3&0&0\\0&0&0&-6&0\\0&0&0&0&0\\91&0&0&0&0\\0&0&28&0&0\end{bmatrix}\)

In the above example, only 7 of 30 elements are nonzero. Storing them in a two-dimensional array wastes memory space. Therefore we use the following representation to store a sparse matrix in an unsorted array of triples, <row, column, value>:

#define MAX_TERMS 1001
int num_row, num_column;
struct Term { int row; int column; int value; } M[MAX_TERMS];

And the above example is stored in the array M as: num_row = 6, num_column = 5;M[0]=<5,2,28>、[1]=<0,0,15>、[2]=<4,0,91>、[3]=<0,3,22>、[4]=<1,1,11>、[5]=<1,2,3>、[6]=<2,3,−6>、[7]=<0,0,0>。The final entry A[7], which contains a zero value, represents the end of the array.

(a) (5 分) Please write the pseudo code of the transpose(Term A[], Term B[]) function that transposes a sparse matrix A[] into another sparse matrix B[]. For example, <4,0,91> in the above example will be converted to <0,4,91> in B[].

(b) (5 分) What is the time complexity for finding the value of an element in row \(i\) and column \(j\), from a sparse matrix with \(N_R\) rows and \(N_C\) columns that contains just \(N\) nonzero elements? Please explain your answer briefly.

(c) (10 分) Please suggest a different representation of sparse matrix, such that finding the value of an element in row \(i\) and column \(j\) from a sparse matrix may be finished in \(O(1)\) constant time complexity in average cases. Please also explain your answer.

(a) 轉置:每個 <row, col, val> 變成 <col, row, val>,行列數對調。為了讓 B 依新的 row(也就是 A 的 column)排好,先數每個 column 有幾項,算出每個 column 在 B 的起始位置

transpose(Term A[], Term B[]):
  n = 0
  while A[n].value != 0: n++                 // 非零項個數(A[n] 是結尾標記)
  B.num_row = A.num_column;  B.num_column = A.num_row
  for c = 0 .. A.num_column-1: count[c] = 0
  for k = 0 .. n-1: count[ A[k].column ]++   // 每個 column 有幾項
  start[0] = 0
  for c = 1 .. A.num_column-1: start[c] = start[c-1] + count[c-1]
  for k = 0 .. n-1:
      p = start[ A[k].column ]++             // 這一項在 B 的位置
      B[p].row    = A[k].column
      B[p].column = A[k].row
      B[p].value  = A[k].value
  B[n].row = B[n].column = B[n].value = 0    // 結尾標記

時間 \(O(N+N_C)\),額外空間 \(O(N_C)\)

簡單版:對 \(c=0..N_C-1\) 各掃一遍 A,凡 column=c 的就依序放進 B,時間 \(O(N_C\cdot N)\);上面是用 counting 省掉重複掃描

(b) 三元組沒有排序,要找 \((i,j)\) 只能從頭掃,每項比對 row、column 是否等於 \((i,j)\);找不到(值為 0)要掃完全部 \(N\) 項

\(O(N)\)(與 \(N_R,N_C\) 無關)

若三元組依 \((row,column)\) 排序,可用 binary search,\(O(\log N)\)

(c) 用 hash table:以 \((i,j)\) 為 key(例如 \(key=i\cdot N_C+j\))、只存非零項;hash function 設計得均勻、table 大小與 \(N\) 同量級(load factor 為常數)

查 \((i,j)\):算 \(h(key)\),到該 bucket 找 key;找到就回傳 value,沒有就回傳 0

平均每個 bucket 只有常數個項目,所以平均 \(O(1)\);空間 \(O(N)\)。最壞(全部撞同一格)\(O(N)\)

hash table(key=\((i,j)\)):平均 \(O(1)\) 查值

615 分

(a) (4 分) “A problem \(D_1\) is polynomial-time reducible to a problem \(D_2\) (\(D_1\le_p D_2\))”. What does the statement mean?

(b) (6 分) The hamiltonian-cycle problem is to determine if there exists a simple cycle that contains each vertex in an undirected graph. The traveling-salesman problem asks the following question: Given a list of cities and the distances between each pair of cities, what is the shortest route that visits each city exactly once and returns to the origin city? Please show how the hamiltonian-cycle problem is reducible to the traveling-salesman problem in polynomial time. Hint: Start with \(G=(V,E)\) which is an instance of the hamiltonian-cycle problem. Construct the instance from \(G\) for the traveling-salesman problem that requires a graph, a cost matrix, and a threshold.

(c) (5 分) Describe briefly the procedure that proves some new problem is NP-complete.

(a) 存在一個 polynomial time 可計算的函數 \(f\),把 \(D_1\) 的任一個 instance \(x\) 轉成 \(D_2\) 的 instance \(f(x)\),並且 \(x\) 的答案是 yes ⇔ \(f(x)\) 的答案是 yes

意義:\(D_2\) 有 polynomial time 解法,\(D_1\) 就有;反過來 \(D_1\) 難,\(D_2\) 至少一樣難

(b) 由 \(G=(V,E)\) 造 TSP 的 instance:

graph:\(G'=(V,E')\),\(E'\) 是 \(V\) 的所有點對(complete graph)

cost matrix:\(c(u,v)=0\)(若 \((u,v)\in E\)),\(c(u,v)=1\)(若 \((u,v)\notin E\))

threshold:\(k=0\)(問是否存在 cost ≤ 0 的 tour)

建構要寫 \(|V|^2\) 個 cost,polynomial time

正確性:

(⇒) \(G\) 有 Hamiltonian cycle \(h\):它在 \(G'\) 是一個經過每點一次的 tour,每條邊都在 \(E\) 中、cost 0,總 cost = 0 ≤ k

(⇐) \(G'\) 有 cost ≤ 0 的 tour:cost 全非負,所以每條邊 cost 都是 0,也就是都在 \(E\) 中,這個 tour 就是 \(G\) 的 Hamiltonian cycle

HAM-CYCLE \(\le_p\) TSP

(c) 證明新問題 \(L\) 是 NP-complete:

① 證 \(L\in\text{NP}\):給一個 certificate,能在 polynomial time 驗證答案

② 選一個已知的 NP-complete 問題 \(L'\)(如 SAT、3-SAT、Hamiltonian cycle)

③ 寫出 polynomial time 的轉換 \(f\):\(L'\) 的 instance → \(L\) 的 instance

④ 證明 \(x\in L'\) ⇔ \(f(x)\in L\),且 \(f\) 在 polynomial time 內算完,得 \(L'\le_p L\);加上 ①,\(L\) 是 NP-complete

715 分

Given a directed graph \(G\):

aecbdf

(a) (5 分) Please show the strongly connected components of \(G\).

(b) (5 分) Please describe how the depth-first search algorithm is applied for finding the strongly connected components in a directed graph.

(c) (5 分) Let \(C\) and \(C'\) be distinct strongly connected components in a directed graph \(G^{*}\). Let \(u,v\in C\), \(u',v'\in C'\), and suppose \(G^{*}\) contains a path from \(u\) to \(u'\). Is it possible that \(G^{*}\) also contains a path from \(v'\) to \(v\)? Give specific reasons for your answer; otherwise, no credit will be given.

(a) 邊:\(e\to a,\ a\to c,\ c\to e,\ c\to d,\ b\to c,\ b\to d,\ d\to e,\ d\to f,\ f\to e,\ f\to b\)

找一條經過全部點的 closed walk:\(a\to c\to d\to f\to b\to c\to e\to a\)(紅色,7 條邊,回到出發點)

closed walk 上的任兩點可互相走到,所以六個點兩兩互達

aecbdf

只有一個 strongly connected component:\(\{a,b,c,d,e,f\}\)(整張圖)

(b) Kosaraju 演算法,兩次 DFS:

① 對 \(G\) 做 DFS,記錄每個點的 finishing time(結束拜訪的先後)

② 計算轉置圖 \(G^{T}\)(所有邊反向)

③ 對 \(G^{T}\) 做 DFS,主迴圈依 finishing time 由大到小挑起點

④ 第二次 DFS 中,每一棵 DFS tree 的點就是一個 strongly connected component

原理:finishing time 最大的點一定在 source component(沒有進入邊的 component),在 \(G^{T}\) 中從它出發只走得到自己這個 component,不會漏進別的。時間 \(O(V+E)\);另一個做法是 Tarjan,一次 DFS 用 low-link 與 stack 找出

(c) 不可能

\(u\) 與 \(v\) 同在 \(C\),所以 \(v\) 走得到 \(u\);\(u'\) 與 \(v'\) 同在 \(C'\),所以 \(u'\) 走得到 \(v'\)

若又有 \(v'\) 到 \(v\) 的路徑:\(u\leadsto u'\leadsto v'\leadsto v\leadsto u\) → \(u\) 與 \(u'\) 互相走得到,也就是在同一個 strongly connected component,與 \(C\ne C'\) 矛盾

不可能(否則 \(C\) 與 \(C'\) 會合成一個 component)

810 分

Suppose that you are offered an opportunity to invest in the X-Computing Corporation. You are allowed to buy one unit of stock only once and then sell it at a later date, buying and selling after the close of trading for the day. To compensate for this restriction, you are allowed to learn the future prices of the stock. The goal is to maximize the profit. For example, given the stock prices in the table below, the best strategy is to buy the stock on ‘Day 8’ and sell it on ‘Day 12’, where the profit is 43 (86−43).

Day1234567891011121314151617
Price8093906585826643618174868159747077

(a) (3 分) Please describe the time complexity if we use a brute force approach.

(b) (7 分) Please describe a dynamic programming approach that solves the problem. Analyze the time and space complexity.

(a) brute force:列舉所有 \((i,j)\),\(i\lt j\)(買 \(i\) 天、賣 \(j\) 天),算 \(p_j-p_i\) 取最大;\(\binom n2\) 個組合,每個 \(O(1)\)

\(O(n^2)\)

(b) 定義 \(m_j\) = 前 \(j\) 天的最低價;\(B_j\) = 在第 \(j\) 天(含)以前買、第 \(j\) 天以前賣能得到的最大利潤

遞迴:\(m_j=\min(m_{j-1},\,p_j)\)  \(B_j=\max\bigl(B_{j-1},\ p_j-m_{j-1}\bigr)\) (\(m_1=p_1,\ B_1=0\))

第 \(j\) 天賣出的最好買點,就是前面 \(j-1\) 天裡最低的那天;最佳解不是第 \(j\) 天賣,就是前 \(j-1\) 天內已經決定

\(j\)1234567891011121314151617
\(p_j\)8093906585826643618174868159747077
\(m_j\)8080806565656543434343434343434343
\(B_j\)013131320202020203838434343434343

\(B_{17}=43\),在第 12 天賣出(\(86-43\)),買點是 \(m_{11}=43\) 那天,第 8 天

時間:掃一遍,每天 \(O(1)\),共 \(O(n)\);空間:只要保留 \(m\)、\(B\) 與最佳買賣日,\(O(1)\)(若整張表都存則 \(O(n)\))

等價做法:令 \(d_j=p_j-p_{j-1}\),答案是 \(d\) 的 maximum subarray,也是 \(O(n)\)(Kadane)

DP:\(O(n)\) 時間、\(O(1)\) 額外空間,最大利潤 43(第 8 天買、第 12 天賣)

910 分

Given a weighted, undirected graph \(G\):

abeghdcf24531513462

(a) (5 分) Please write down the edges selected in order when using Prim's algorithm to construct the minimal spanning tree of \(G\). Start from vertex \(a\).

(b) (5 分) Let \((u,v)\) be a minimum-weight edge in a graph \(G\). Please show that \((u,v)\) must belong to some minimum spanning tree of \(G\).

邊:\(ab=2,\ ac=4,\ be=5,\ eg=3,\ bg=1,\ bd=5,\ bf=1,\ cd=3,\ df=4,\ dh=6,\ gh=2\)

(a) 每步從「樹內到樹外」的邊中選最輕的;權重相同取標號較小的點

步樹內的點候選邊(樹內→樹外)選
1aab 2、ac 4ab(2)
2a, bac 4、be 5、bg 1、bd 5、bf 1bf(1)
3a, b, fac 4、be 5、bg 1、bd 5、fd 4bg(1)
4a, b, f, gac 4、be 5、bd 5、fd 4、ge 3、gh 2gh(2)
5a, b, f, g, hac 4、be 5、bd 5、fd 4、ge 3、hd 6ge(3)
6a, b, e, f, g, hac 4、bd 5、fd 4、hd 6ac(4)
7a, b, c, e, f, g, hcd 3、bd 5、fd 4、hd 6cd(3)

abeghdcf24531513462

步驟 6 的 ac(4)與 fd(4)同權重,改選 fd 再選 cd,得到另一棵 MST,總和一樣是 16

選取順序:\(ab,\ bf,\ bg,\ gh,\ ge,\ ac,\ cd\),總權重 \(2+1+1+2+3+4+3=16\)

(b) 令 \(T\) 是任一棵 MST。若 \((u,v)\in T\) 就完成

否則把 \((u,v)\) 加進 \(T\),\(T\) 中 \(u\) 到 \(v\) 有一條路徑,加上 \((u,v)\) 形成一個 cycle,這個 cycle 裡還有別的邊 \(e'\)

\((u,v)\) 是 \(G\) 中權重最小的邊,所以 \(w(u,v)\le w(e')\)

\(T'=T+(u,v)-e'\) 仍然連通、無 cycle、有 \(|V|-1\) 條邊,是 spanning tree,\(w(T')=w(T)+w(u,v)-w(e')\le w(T)\)

\(T\) 是 MST,所以 \(w(T')=w(T)\),\(T'\) 也是 MST,而且含 \((u,v)\) 得證

若最小邊不只一條,只保證「某一棵」MST 含它,不一定每一棵都含

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

國立臺灣師範大學 109–115 的詳解收錄在付費版;106–115 全年度完整詳解共 309 頁,逐題推導。

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

其他年度與考科

同一年的其他科

同一科的其他年度

聯絡我們

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

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

william.chou.123123@gmail.com