(V) (35 points) In the data structure deque, elements can be added to one end and removed from the other. Different from queues, a deque allows elements to be added to and removed from both ends.
(a) (15 points) Given a deque with a permutation of the numbers from 1 to \(n\) (\(n\ge5\)), we want to remove all of the numbers to form a sequence \(\langle a_1,a_2,a_3,\ldots,a_n\rangle\) that maximizes the alternative sum (\(a_1-a_2+a_3-\cdots\pm a_n\)), where \(a_1\) is the first number removed, \(a_2\) is the second number, and so on. For example, suppose a deque contains 5 numbers as follows: (head) 2, 3, 1, 4, 5 (rear). One possible generated sequence is \(\langle5,2,4,1,3\rangle\) whose alternative sum is 9.
(1) (5 points) Give an example to demonstrate that the problem cannot be solved by a greedy algorithm, which first removes the larger one of the two ends, then removing in the order of the smaller one, the larger one, the smaller one, etc. Show your calculation.
(2) (10 points) Devise an \(O(n^2)\) algorithm to generate the optimal sequence for a given deque. Explain how your algorithm works on the example you give previously.
(1) 反例:head 3, 1, 2, 4, 5 rear
greedy:
兩端 (3, 5) 取大 → 5,剩 3, 1, 2, 4 → \(+5\)
兩端 (3, 4) 取小 → 3,剩 1, 2, 4 → \(-3\)
兩端 (1, 4) 取大 → 4,剩 1, 2 → \(+4\)
兩端 (1, 2) 取小 → 1,剩 2 → \(-1\)
最後 2 → \(+2\)
\(5-3+4-1+2=7\)
另一種取法 \(\langle3,1,5,2,4\rangle\):取 head 3、head 1、rear 5、head 2、剩 4
\(3-1+5-2+4=9\gt7\) → greedy 不是最佳
題目給的範例 2, 3, 1, 4, 5 用 greedy 剛好也是 9,不能當反例
(2) DP。第 \(k\) 個被取出的數符號是 \(+\)(\(k\) 奇數)或 \(-\)(\(k\) 偶數)
剩下區間 \(A[i..j]\),長度 \(\ell=j-i+1\),下一個是第 \(n-\ell+1\) 個,符號只由 \(\ell\) 決定:\(s_\ell=+1\)(\(n-\ell\) 為偶)、\(-1\)(\(n-\ell\) 為奇)
\(D[i][j]\)=取完 \(A[i..j]\) 能得到的最大(帶符號)總和
\(D[i][j]=\max\big(s_\ell A[i]+D[i+1][j],\ \ s_\ell A[j]+D[i][j-1]\big)\),\(D[i][i-1]=0\)
依長度 \(\ell=1,2,\ldots,n\) 填表,答案 \(D[1][n]\);每格記錄選頭或選尾,從 \(D[1][n]\) 往回追就得到序列
狀態 \(O(n^2)\) 個,每個 \(O(1)\) → \(O(n^2)\) 時間
範例 \(A=(3,1,2,4,5)\),\(n=5\):\(\ell=5,3,1\) 符號 \(+\);\(\ell=4,2\) 符號 \(-\)
| \(\ell\)(符號) | \(D[1][\cdot]\) | \(D[2][\cdot]\) | \(D[3][\cdot]\) | \(D[4][\cdot]\) | \(D[5][\cdot]\) |
| 1 (+) | 3 | 1 | 2 | 4 | 5 |
| 2 (−) | \(D[1][2]=2\) | \(D[2][3]=1\) | \(D[3][4]=2\) | \(D[4][5]=1\) | |
| 3 (+) | \(D[1][3]=4\) | \(D[2][4]=5\) | \(D[3][5]=7\) | | |
| 4 (−) | \(D[1][4]=2\) | \(D[2][5]=6\) | | | |
| 5 (+) | \(D[1][5]=9\) | | | | |
例:\(D[1][5]=\max(3+D[2][5],\ 5+D[1][4])=\max(3+6,\ 5+2)=9\) → 先取 head 3
\(D[2][5]=\max(-1+D[3][5],\ -5+D[2][4])=\max(6,\ 0)\) → 取 head 1
\(D[3][5]=\max(2+D[4][5],\ 5+D[3][4])=\max(3,\ 7)\) → 取 rear 5
\(D[3][4]=\max(-2+D[4][4],\ -4+D[3][3])=\max(2,\ -2)\) → 取 head 2,最後 4
序列 \(\langle3,1,5,2,4\rangle\),最大交替和 \(9\)