Greedy Algorithm 实例

喜你入骨 提交于 2020-04-06 19:33:08

Algorithm Design Techniques - 1

##Greedy Algorithm##

note:

It works only if local optimum is equal to global optimum

###1. Approximate Bin Packing### ####The Knapsack problem####

问题大意:给定n种物品和一个背包,背包容量为Sum,对于每一个物品i,它的重量为W(i), 价值为p(i)。 要怎样才能使背包装的物品的价值最高。

<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>

#####0-1你背包问题#####

问题大致描述: 没见物品要么不放要么放,不能把物品拆成小份(其他基本同上)

通常采用动态规划算法来解决

针对该问题的算法主要思想:(待续

####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;
   }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!