11.07.2015 Views

課本第六章習題(部分)參考解答

課本第六章習題(部分)參考解答

課本第六章習題(部分)參考解答

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

資 料 結 構 第 六 章 習 題 參 考 解 答課 本 : Data Structures Using C and C++by Y. Langsam, M. J. Augenstein and A. M.Tenenbaum1.1. Design an algorithm that prints all sets of six positive integers a 1 , a 2 , a 3 , a 4 , a 5 anda 6 such that a 1 a 2 a 3 n and a 1 < a 4 a 5 a 6 n, and the sum of the squares ofa 1 , a 2 and a 3 equals the sum of the squares of a 4 , a 5 and a 6 . Note that youralgorithm should be of O(n 3 log n) time.Solution:滿 足 a 的 所 有 情 形 , , 與 滿 足 a 的 所 有 情 形 , , 相 同 , 找 出 滿 足 a 形 式 的 所 有 情 形 ,計 算 , , , 之 值 , 與 , , , , , 一 併 記 錄 於 陣 列 中 , 總 個數 介 於 與 , 此 步 驟 時 間 複 雜 度 為 。接 著 排 序 陣 列 , 主 要 依 據 的 大 小 , 若 之 值 相 等 , 次 要 則 依 , 的大 小 , 較 小 者 於 前 頭 。 因 元 素 數 量 約 為 ( 略 小 於 ) , 所 需 的 時 間 複 雜 度 為 log ∙3log log 。排 序 後 , 總 和 相 等 者 , 將 會 排 在 隔 鄰 ( 有 可 能 連 續 h 組 的 總 和 相 等 )。 因 此 ,依 序 檢 查 陣 列 中 的 元 素 , 檢 查 總 和 是 否 與 前 組 相 等 。 若 相 等 , 則 印 出 這1 組 解 , , , , , , , , , , , , 其 中 為 小 於 等 於 的 正 整 數 。假 定 最 大 可 能 的 為 常 數 , 此 步 驟 時 間 複 雜 度 亦 為 。如 下 圖 為 9 時 , 此 演 算 法 的 部 份 示 意 圖 : , , , , , , , , , , , …3,1,1,1...82,3,3,883,1,1,983,3,5,7 (1,1,9,3,5,7)84,2,4,886,1,2,986,1,6,7 (1,2,9,1,6,7)86,5,5,6 (1,2,9,5,5,6)(1,6,7,5,5,6)88,4,6,689,2,2,989,2,6,7 (2,2,9,2,6,7)89,3,4,8 (2,2,9,3,4,8)(2,6,7,3,4,8)90,1,5,890,4,5,7 (1,5,8,4,5,7)91,1,3,993,2,5,8...243,9,9,9


附 件 , C++ 程 式 實 作 >#include #include #include using namespace std;class record {public:int p,q,r,sum;record(int p,int q,int r) : p(p),q(q),r(r),sum(p*p+q*q+r*r) {}bool operator


2. The two-way insertion sort is a modification of the simple insertion sort asfollows: A separate output array of size n is set aside. This output array acts as acircular structure. (The right position of x[i] is x[i+1] if 0 i n-2, and the rightposition of x[n-1] is x[0].) x[0] is placed into the middle element of the array.Once a contiguous group of elements are in the array, room for a new element ismade by shifting all smaller elements one step to the left or all larger element onestep to the right. The choice of which shift to perform depends on which wouldcause the smallest amount of shifting. Use the following 7 elements to explainhow this algorithm works: 25, 48, 37, 12, 86, 57, 33.紅 色 :inserted; 綠 色 :shifted。25 2548373725482548123737254825481286125786


37334825571286

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!