深入理解動態規劃的一系列問題(9)
今天介紹的動態規劃問題是個有意思的問題,名字叫做Covering,問題描述如下:有k朵不同尺寸的花,現在天氣變涼,為了防止花被霜凍,現在需要生產不超過n種尺寸的遮罩來保護這些花,條件是n≤k,并且允許大尺寸的遮罩保護小尺寸的花朵,對應生產k種不同尺寸的遮罩,有不同的生產成本,目標就是給出最低成本及方案。舉個具體例子來說明這個問題,假設k=10,即有10朵大小不一的花,將這些花按尺寸從小到大排序并編號,為0~k-1,生產對應尺寸遮罩的成本為c={1,4,5,7,8,12,13,18,19,21},n=3,即現有條件只允許生產3種尺寸的遮罩,那么最優方案是什么,最低成本是多少?
因為限制了n=3,也就是需要我們在c這個成本序列里添加兩個分界把這個序列分為3個子序列,然后每部分按照最大的那個尺寸去加和,然后最后加和3個子序列和來確定成本。如果我們把分界定為3和6(第3個和第6個,指定下標),那么需要生產的其實是c[3]=7和c[6]=13以及c[9]=21的遮罩,而總和C=7*size(0~3)+13*size(4~6)+21*size(7~9)=7*4+13*3+21*3=130。而要想求得最優方案和最低成本,我們明顯需要劃分出所有可能的組合而求最小值,這典型的DP求解。
DP求解的第一步就是定義狀態,這個在之前也說過無數次了,狀態定義是狀態轉移方程的基礎。那么這個問題因為涉及到遮罩和花朵兩種對象,所以我們自然的想到用(j,l)來定義狀態,其中j是有多少種遮罩需要確定,l是尚未被確定遮罩的花朵中的最大尺寸的花朵(位置下標)。通過這個定義,可以知道目標函數是求f(n,k-1),而基礎條件是f(1,l)=(l+1)*c[l],當j=1時。DPFE為f(j,l)=min {(l-k)*c[l]+f(j-1,l-k)}當j>1時,且k∈(j-2,…,l-1)。
綜上,最優分隔應該是4,6和9,顯然9是必須在這個分隔組里的。那么最低成本C=8*size(0~4)+13*size(5~6)+21*size(7~9)=8*5+13*2+21*3=129。
source code:
1: /*
2: * Copyright (C) 2013 changedi
3: *
4: * Licensed under the Apache License, Version 2.0 (the "License");
5: * you may not use this file except in compliance with the License.
6: * You may obtain a copy of the License at
7: *
8: * http://www.apache.org/licenses/LICENSE-2.0
9: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package com.jybat.dp;
17:
18: //optimal COVering problem
19: public class COV {
20: // cost of cover sizes 0,1,..,9 in dollar
21: private static int[] cost = { 1, 4, 5, 7, 8, 12, 13, 18, 19, 21 };
22:
23: public static double f(int numberOfCoverSizes, int largestSize) {
24: //numberOfCoverSizes denotes the stage number in this problem
25: if (numberOfCoverSizes == 1)
26: return (largestSize + 1) * cost[largestSize];
27: double min = Double.MAX_VALUE;
28: for (int nextCoverSize = numberOfCoverSizes - 2; nextCoverSize <= largestSize - 1; nextCoverSize++) {
29: double t = (largestSize - nextCoverSize) * cost[largestSize]
30: + f(numberOfCoverSizes - 1, nextCoverSize);
31: if (t < min)
32: min = t;
33: }
34: return min;
35: }
36:
37: /**
38: * @param args
39: */
40: public static void main(String[] args) {
41: System.out.println(f(3, 9));
42: }
43:
44: }
posted on 2014-05-06 15:55 changedi 閱讀(1758) 評論(0) 編輯 收藏 所屬分類: 算法