##Greedy Algorithm##node
note:算法
It works only if local optimum is equal to global optimumapp
###1. Approximate Bin Packing### ####The Knapsack problem####ide
問題大意:給定n種物品和一個揹包,揹包容量爲Sum,對於每個物品i,它的重量爲W(i), 價值爲p(i)。 要怎樣才能使揹包裝的物品的價值最高。ui
<pre><code> Example : n = 3, M = 20, (p1, p2, p3) = (25, 24, 15) (w1, w2, w3)= (18, 15, 10) Solution is...? ( 0, 1, 1/2 ) P = 31.5 這是一種最理想化的情形。(由於這種算法將一個物品當作由很小的部分組成。你能夠把一個物品分開) </code></pre>code
#####0-1你揹包問題#####ci
問題大體描述: 沒見物品要麼不放要麼放,不能把物品拆成小份(其餘基本同上)input
一般採用
動態規劃算法
來解決it針對該問題的算法主要思想:(
待續
)io
####The Bin Packing Problem####
問題大意:有n種物品,各自大小爲S(n); 怎樣用最少的箱子把他們所有裝完。
NP Hard
On-line Algorithm
: (Bad) There are inputs that force any on-line bin-packing algorithm to use at least 5/3 the optimal number of bins.
Next Fit
: Let M be the optimal number of bins required to pack a list I of items. Then next fit never uses more than 2M bins. There exist sequences such that next fit uses 2M – 2 bins.再放下一個物品前,先檢測前一個箱子能不能放下該物品。
<!-- lang: cpp --> void NextFit ( ) { read item1; while ( read item2 ) { if ( item2 can be packed in the same bin as item1 ) place item2 in the bin; else create a new bin for item2; item1 = item2; } /* end-while */ }
First Fit
: Let M be the optimal number of bins required to pack a list I of items. Then first fit never uses more than 17M / 10 bins. There exist sequences such that first fit uses 17(M – 1) / 10 bins.
<!-- lang: cpp --> void FirstFit ( ) { while ( read item ) { scan for the first bin that is large enough for item; if ( found ) place item in that bin; else create a new bin for item; } /* end-while */ }
Best Fit
: Place a new item in the tightest spot among all bins. T = O( N log N ) and bin no. < 1.7M 注意,總的來講這個仍是On-line,因此不是最優Off-Line Algorithm
: View the entire item list before producing an answer.Solution : Sort the items into non-increasing sequence if sizes. Then apply the first or best Fit.
Let M be the optimal number of bins required to pack a list I of items. Then first fit decreasing never uses more than 11M / 9 + 1 bins. There exist sequences such that first fit decreasing uses 11M / 9 bins.
###2. Huffman Codes###
<!-- lang: cpp --> void Huffman ( PriorityQueue heap[ ], int C ) { consider the C characters as C single node binary trees, and initialize them into a min heap; for ( i = 1; i < C; i++ ) { create a new node; /* be greedy here */ delete root from min heap and attach it to left_child of node; delete root from min heap and attach it to right_child of node; weight of node = sum of weights of its children; /* weight of a tree = sum of the frequencies of its leaves */ insert node into min heap; } }