免費詳解 / 中正 / 軟體 / 102

102 中正資工所考古題解答|軟體逐題詳解

102 中正資工所軟體考古題的逐題詳解,共 17 題,免費公開。

逐題詳解

112%

Multiple-choice questions.(單選題)

1.1. (2%) Which of the following is an illegal use of function put? (a) cout.put('A'); (b) cout.put("A"); (c) cout.put('A').put('\n'); (d) cout.put(65);

1.2. (2%) Assume that t is an object of class Test, which has member functions a(), b(), c() and d(). If the functions a(), b(), c() all return references to an object of class Test (using the dereference this pointer) and function d() returns void, which of the following statements will not produce a syntax error: (a) t.a().b().d(); (b) a().b().t; (c) t.d().c(); (d) t.a().t.d();

1.3. (2%) A function that modifies an array by using pointer arithmetic such as ++ptr to process every value should have a parameter that is: (a) A non-constant pointer to non-constant data. (b) A non-constant pointer to constant data. (c) A constant pointer to non-constant data. (d) A constant pointer to constant data.

1.4. (2%) A function prototype does not have to ______. (a) include argument names (b) end with a semi-colon (c) agree with the function header (d) match with all calls of the function

1.5. (2%) Recursion is memory-intensive because: (a) Recursive functions tend to declare many local variables. (b) Previous function calls are still open when the function call itself and the activation records of these previous calls still occupy space on the call stack. (c) Many copies of the function code are created. (d) It requires large data values.

1.6. (2%) static member functions: (a) Can use this pointer. (b) Can access only other static member functions and static data members. (c) Cannot be called until an object of their class is instantiated. (d) Can be declared const as well.

1.1 put 收一個 char;(b) 的 "A" 是字串(const char*),不能轉成 char;(c) 回傳 ostream& 可串接;(d) 65 轉成 'A' → (b)

1.2 a()、b() 回傳 Test& 可以一路接,最後 d() 回傳 void 沒問題;(b) 前面沒有物件;(c) void 後面不能再接 .c();(d) Test 裡沒有成員 t → (a)

1.3 要改內容:資料不能是 const;要 ++ptr:指標本身不能是 const → (a)

1.4 prototype 只需要參數型態,名稱可省(int max(int,int););(b)(c)(d) 都是必要的 → (a)

1.5 前面每層呼叫都還沒 return,activation record 全留在 call stack 上;function code 只有一份 → (b)

1.6 static member function 沒有 this,所以只能直接用其他 static 成員,也不能宣告 const;不需要物件就能用 Class::f() 呼叫 → (b)

1.1 (b) 1.2 (a) 1.3 (a) 1.4 (a) 1.5 (b) 1.6 (b)

23%

Write a C++ function bool is_palindrome(const char s[]) that returns true if and only if the C-string s reads the same forward and backward (e.g., "mom" and "deed").

兩個 index 從頭尾往中間走,遇到不相等就 false;相遇仍沒失敗就是 true

#include <cstring>
bool is_palindrome(const char s[]) {
    int i = 0, j = (int)strlen(s) - 1;
    while (i < j) {
        if (s[i] != s[j]) return false;
        i++; j--;
    }
    return true;
}

空字串 j=-1,迴圈不跑,回傳 true;strlen 轉成 int,避免空字串時 unsigned 減 1 繞回

34%

What is the output of the following C code?

#include <stdio.h>
void main() {
    int i, s;
    for (i = 0, s = 0; i <= 5; ) {
        s += ++i;
    }
    printf("%d\n", s);
}

++i 先加再取值;條件檢查在加之前:

檢查時 ii ≤ 5++is
0是11
1是23
2是36
3是410
4是515
5是621
6否

i = 5 時條件仍成立,所以加到 6:\(1+2+\cdots+6=21\)

21

44%

What is the output of the following C code?

#include <stdio.h>
void main() {
    printf("%d, %d, %d\n", foo(2), foo(4), foo(6));
}

int foo(int n) {
    int s = 0;
    switch (n) {
        case 1: s = s + n;
        case 2: s = s + 2 * n; break;
        case 3: s = s + 3 * n; break;
        case 4: s = s + 4 * n;
        default: s = s + 5 * n; break;
    }
    return s;
}

沒有 break 的 case 會一路往下掉(fall through)

foo(2):case 2,\(s=2\cdot2=4\),break

foo(4):case 4,\(s=4\cdot4=16\),沒 break,接著 default:\(s=16+5\cdot4=36\)

foo(6):直接 default,\(s=5\cdot6=30\)

printf 參數的求值順序沒規定,但 foo 沒有副作用,不影響輸出

4, 36, 30

54%

What is the output of the following C code?

#include <stdio.h>
void main() {
    int m = 3, n = 5;
    foo(m, n);
    printf("%d, %d\n", m, n);
}

void foo(int x, int y) {
    int z;
    z = x;
    x = y;
    y = z;
}

C 是 call by value,foo 交換的是 x、y 兩個複本,m、n 沒變

要真的交換要傳 pointer:void foo(int *x, int *y),呼叫 foo(&m, &n)

3, 5

64%

What is the output of the following C code?

#include <stdio.h>
void main() {
    int m = 3, n = 5, o = 7;
    if (m < n || (o = m + 2 >= n)) m = o;
    printf("%d, %d\n", m, o);
}

|| 左邊 m < n(3 < 5)為真,short-circuit,右邊 (o = m + 2 >= n) 不會執行,o 仍是 7

條件成立,m = o → \(m=7\)

就算右邊有執行,>= 優先權高於 =,也是 o = (m+2 >= n),o 會變成 0 或 1,不會是 5

7, 7

74%

What is wrong with the following C code?

#include <stdio.h>
void main() {
    int m = 3, n = 5, *o;
    o = goo(m);
    foo(m, n);
    printf("%d\n", *o);
}

void foo(int x, int y) {
    int z;
    z = x;
    x = y;
    y = z;
}

int * goo(int n) {
    int z;
    z = n * n;
    return &z;
}

主要問題:goo 回傳 local variable z 的位址

z 在 goo 的 stack frame 上,goo return 後那塊空間就釋放;o 成了 dangling pointer

之後呼叫 foo 會重用同一塊 stack,*o 的值是 undefined behavior,不保證是 9

改法:goo 用 malloc 配置再回傳(呼叫端 free),或直接回傳 int

另外兩個小問題:foo 是 call by value,交換對 m、n 沒作用;foo、goo 在 main 之後才定義又沒有 prototype,goo 會被當成回傳 int 的隱含宣告,跟後面的 int * 衝突,要在 main 前補 prototype

goo 回傳 local variable 的位址(dangling pointer)

815%

Give the output of the following C++ code.

#include <iostream>
using namespace std;

class A {
  public:
    void print1() { cout << "A1" << endl; }
    virtual void print2() { cout << "A2" << endl; }
    void test() { print1();
                  print2(); }
};

class B: public A {
  public:
    void print1() { cout << "B1" << endl; }
};

class C: public B {
  public:
    void print2() { cout << "C2" << endl; }
};

int main()
{
  A *p1 = new A;
  B objB;
  B *p2 = &objB;
  C objC;

  p1->test();
  (*p2).test();
  objC.test();

  return 0;
}

test() 定義在 A,裡面的 print1()、print2() 就是 this->print1()、this->print2(),this 型態是 A*

print1 不是 virtual,看靜態型態 A,一律呼叫 A::print1(B 的 print1 只是遮蔽,不是 override)

print2 是 virtual,看物件實際型態

呼叫實際型態print1print2
p1->test()AA1A2
(*p2).test()BA1A2(B 沒 override)
objC.test()CA1C2

A1 A2 A1 A2 A1 C2(每個一行)

97%

Suppose \(A\) is a sorted array with \(N\) elements. If we randomly choose \(N/3\) elements of the array and exchange them with their neighbors. What algorithm will be able to sort the resulting array in \(O(N)\) time complexity? Explain your answer.

用 insertion sort

insertion sort 時間 \(O(N+I)\),\(I\) 是 inversion 數:內層每往左移一格,剛好消掉一個 inversion

原本已排好,\(I=0\);和相鄰元素交換一次,只改變那一對的先後,inversion 數恰好改變 1

\(N/3\) 次交換後 \(I\le N/3\),時間 \(O\!\left(N+\dfrac N3\right)=O(N)\)

對比:merge sort、heap sort 不管輸入怎樣都是 \(\Theta(N\log N)\),吃不到「幾乎排好」的好處

insertion sort,\(O(N+I)=O(N)\)

108%

(a) (4%) Please describe Open Addressing Hash data structure. (b) (4%) If we need to delete elements from the hash data structure, can we use Open Addressing? Why?

(a) 所有 key 都直接放在 hash table 的 array 裡,不另外掛 linked list

collision 時依固定的 probe sequence 找下一個空格:

linear probing \(h(k,i)=(h'(k)+i)\bmod m\)

quadratic probing \(h(k,i)=(h'(k)+c_1i+c_2i^2)\bmod m\)

double hashing \(h(k,i)=(h_1(k)+i\,h_2(k))\bmod m\)

search 沿同一條 probe sequence 找,找到 key 就成功,遇到空格就表示不存在;load factor \(\alpha=n/m\le1\)

(b) 可以,但不能直接把格子清成空的,要用 lazy deletion

search 是「遇到空格就停」;刪掉的格子若變回空格,原本因 collision 排在它後面的 key 就找不到了

做法:刪除時放 DELETED 標記(tombstone),search 當成有東西、繼續往下找;insert 可把它當空位重用

缺點:標記越積越多,search 時間不再只看 load factor;刪除很頻繁時 separate chaining 比較適合

(b) 可以,用 lazy deletion(標記 deleted)

115%

What is the postfix expression of \((A*(C+D))/(B-E)\)?

\(C+D\) → \(CD+\)

\(A*(C+D)\) → \(ACD+*\)

\(B-E\) → \(BE-\)

相除:\(ACD+*\ BE-\ /\)

\(A\ C\ D\ +\ *\ B\ E\ -\ /\)

125%

The matrix chain multiplication problem is to find the optimal way to multiply a chain of \(n\) matrices \(A_1,A_2,\dots,A_n\) with minimum number of scalar multiplications. Let \(d_{i-1}\times d_i\) be the dimension of \(A_i\), and \(C(p,q,r)\) be the minimum number of scalar multiplications to multiply two matrices of dimension \(p\times q\) and \(q\times r\), respectively. Let \(m[i,j]\) denote the minimum number of scalar multiplications to multiply sub-chain \(A_i,A_{i+1},\dots,A_j\). Give a recursive formula for \(m[i,j]\).

在 \(A_k\) 與 \(A_{k+1}\) 之間切開:左半 \(A_i\cdots A_k\) 是 \(d_{i-1}\times d_k\),右半 \(A_{k+1}\cdots A_j\) 是 \(d_k\times d_j\),最後再乘一次

\(m[i,j]=\begin{cases}0 & i=j\\[2pt]\displaystyle\min_{i\le k\lt j}\bigl\{m[i,k]+m[k+1,j]+C(d_{i-1},d_k,d_j)\bigr\} & i\lt j\end{cases}\)

兩個矩陣相乘的最少純量乘法數 \(C(p,q,r)=pqr\)

\(m[i,j]=\min_{i\le k\lt j}\{m[i,k]+m[k+1,j]+C(d_{i-1},d_k,d_j)\}\),\(m[i,i]=0\)

135%

Give a recursive procedure in pseudo code for depth first search on graphs, which returns \(d[v]\), \(f[v]\) and \(\pi[v]\), for every vertex \(v\), where \(d[v]\), \(f[v]\) and \(\pi[v]\) denote the discovery time, finish time and predecessor of \(v\), respectively.

DFS(G)
    for each vertex u in G.V
        color[u] = WHITE;  π[u] = NIL
    time = 0
    for each vertex u in G.V
        if color[u] == WHITE
            DFS-VISIT(G, u)

DFS-VISIT(G, u)
    time = time + 1
    d[u] = time
    color[u] = GRAY
    for each v in G.Adj[u]
        if color[v] == WHITE
            π[v] = u
            DFS-VISIT(G, v)
    color[u] = BLACK
    time = time + 1
    f[u] = time

WHITE 未發現、GRAY 已發現但還沒做完、BLACK 整棵子樹做完

外層迴圈確保不連通的部分也會走到;總時間 \(O(V+E)\)

145%

Consider the following function on nonnegative integers \(m\) and \(n\).

\(f(m,n)=\begin{cases}0 & \text{if }m=0\text{ or }n=0\\ \max\{f(m-1,n-1)+g(m,n),\ f(m-1,n),\ f(m,n-1)\} & \text{otherwise}\end{cases}\)

Let \(G(m,n)\) be an efficient procedure to compute \(g(m,n)\). Namely, the running time of \(G(m,n)\) is bounded by a polynomial of \(m\) and \(n\). Give an efficient procedure \(F(m,n)\) to compute \(f(m,n)\), using procedure \(G(m,n)\).

直接照遞迴算,同一個 \(f(i,j)\) 會被重算指數次。\(f(i,j)\) 只依賴左、上、左上三格,開 \((m+1)\times(n+1)\) 的表,由小到大填(dynamic programming):

F(m, n)
    for i = 0 to m: f[i][0] = 0
    for j = 0 to n: f[0][j] = 0
    for i = 1 to m
        for j = 1 to n
            f[i][j] = max( f[i-1][j-1] + G(i, j),
                           f[i-1][j],
                           f[i][j-1] )
    return f[m][n]

共 \(mn\) 格,每格呼叫一次 \(G\);若 \(G(i,j)\) 的時間以 \(p(m,n)\) 為上界,總時間 \(O(mn\cdot p(m,n))\),仍是 \(m,n\) 的多項式

填 \(f[i][j]\) 時,同一列左邊一格與上一列都已填好,順序沒問題

155%

What is the lower bound of time complexity for any comparison-based sorting algorithm (e.g., bubble sort)? Justify your answer.

任何 comparison sort 都可畫成 decision tree:內部節點是一次比較,leaf 是一種排列結果

\(n\) 個元素有 \(n!\) 種排列,每種都要出現在某個 leaf → leaf 數 \(\ge n!\)

高度 \(h\) 的 binary tree 至多 \(2^h\) 個 leaf,worst case 比較次數 = \(h\):

\(2^h\ge n!\ \Rightarrow\ h\ge\log_2n!\ge\log_2\left(\dfrac n2\right)^{n/2}=\dfrac n2\log_2\dfrac n2=\Omega(n\log n)\)

merge sort、heap sort 是 \(O(n\log n)\),所以這個下界是緊的

\(\Omega(n\log n)\)

165%

The order statistics (finding the \(i\)-th smallest element) can be solved by dividing numbers into groups of five, finding the "median of medians of 5-element groups," and recursively solving partitioned subproblems. What is the complexity of a new algorithm which divides numbers into groups of three (instead of five) elements?

\(n/3\) 組各取 median,再遞迴找這些 median 的 median \(x\),花 \(T(n/3)\)

比 \(x\) 小的 median 有一半的組,約 \(n/6\) 組,每組至少 2 個元素 \(\le x\),所以至少約 \(n/3\) 個元素 \(\le x\);同理至少約 \(n/3\) 個 \(\ge x\)

partition 後遞迴的那一邊最多約 \(2n/3\):

\(T(n)=T\!\left(\dfrac n3\right)+T\!\left(\dfrac{2n}3\right)+O(n)\)

兩個子問題大小加起來剛好 \(n\),recursion tree 每層工作量都是 \(cn\),深度 \(\log_{3/2}n\) → \(T(n)=O(n\log n)\)

5 個一組:\(T(n/5)+T(7n/10)+O(n)\),\(\tfrac15+\tfrac7{10}\lt1\),每層工作量等比遞減,才是 \(O(n)\);3 個一組時 \(\tfrac13+\tfrac23=1\),不再遞減

\(O(n\log n)\),不再是線性

175%

The vertex cover problem asks if there exists a set of vertices with size \(k\) (called vertex cover) incident to each edge in the graph. Prove the vertex cover problem is NP-complete by reduction from the clique problem.

(1) VERTEX-COVER ∈ NP:certificate 是點集合 \(V'\);檢查 \(|V'|=k\),掃過每條邊確認至少一個端點在 \(V'\),\(O(V+E)\)

(2) CLIQUE \(\le_p\) VERTEX-COVER

給 CLIQUE 的 instance \(\langle G=(V,E),k\rangle\),建 complement graph \(\overline G=(V,\overline E)\),輸出 \(\langle\overline G,\ |V|-k\rangle\);建 \(\overline G\) 需 \(O(V^2)\),polynomial time

Claim:\(G\) 有大小 \(k\) 的 clique ⟺ \(\overline G\) 有大小 \(|V|-k\) 的 vertex cover

(\(\Rightarrow\)) \(V'\) 是 \(G\) 的 clique,\(|V'|=k\)。任取 \((u,v)\in\overline E\),\((u,v)\notin E\),\(u,v\) 不會都在 \(V'\)(否則 clique 缺一條邊),至少一個在 \(V-V'\);所以 \(V-V'\) 蓋住 \(\overline G\) 所有邊,大小 \(|V|-k\)

(\(\Leftarrow\)) \(C\) 是 \(\overline G\) 的 vertex cover,\(|C|=|V|-k\)。任取 \(u,v\in V-C\),若 \((u,v)\in\overline E\),這條邊兩端都不在 \(C\),與 \(C\) 是 vertex cover 矛盾,所以 \((u,v)\in E\);\(V-C\) 在 \(G\) 中兩兩相連,是大小 \(k\) 的 clique

CLIQUE 是 NP-complete,由 (1)(2),VERTEX-COVER 是 NP-complete 得證

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

國立中正大學 109–115 的詳解收錄在付費版;106–115 全年度完整詳解共 351 頁,逐題推導。

購買 · NT$ 850 看中正其他免費詳解

其他年度與考科

同一年的其他科

同一科的其他年度

聯絡我們

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

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

william.chou.123123@gmail.com