深入理解動態規劃的一系列問題(13)
今天介紹的這個問題還是一個任務調度的問題(Flowshop問題),每個過程i有兩個任務A和B,其中有個約束,那就是A一定要在B之前完成,任務A和B分別由兩個處理器完成,編號為1和2,每個過程i有對應自己任務的完成時間,選擇如何調度這些過程,會產生不同的任務總體完成時間,問題的目標就是要找到最佳完成時間的策略。舉例來講,有4個過程為{0,1,2,3},每個過程對應的A任務完成時間為{3,4,8,10},B任務完成時間為{6,2,9,15},如果處理器按照這個順序去處理任務,依據約束條件,完成過程如下表表示:
如果用DP去求解這個問題,首先定義狀態,我們定義過程d的A任務完成時間為pd,B任務完成時間為qd,那么引入一個虛擬階段號k,k表示上一次被確認調度的A和B任務各自完成中間那段流失的時間(可能不是很好理解,這里解釋一下,為什么取這個值作為狀態,首先對于pd和qd這都是固定計算成本,那么導致任務不能連續運轉的原因就是有A在B前完成這個約束,對于上面的例子,我們看到B3任務并不能在B2任務結束后馬上開始,而一定要等到A3任務結束才可以,B2結束后到A3結束前這段時間即15-11這4個時間單位的時間就是這里的k了,定義了這個k后,我們就可以知道目標狀態是要使k=0且未被調度的任務集合),定義S為剩余的過程集合,所以狀態為(k,S),這個狀態對于一個過程的A和B任務如果沒有延遲(k<pd),那么k=qd,反之有延遲則延遲時間為max(k-pd,0),所以一個調度過程d開始后的時間成本會記為A任務時間pd+延遲時間max(k-pd,0)+B任務時間qd。所以DPFE即f(k,S)=min d∈S{pd+f(max(k-pd)+qd,S-wmqeeuq)}。初始狀態對于S是空集,那么f(k,S)=k。于是對于上面的具體問題,方程求解最優時間是38,決策序列為d1=0,d2=2,d3=3,d4=1。
過程源碼如下:
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: import java.util.HashSet;
19: import java.util.Set;
20:
21: //Flowshop Problem
22: public class FLOWSHOP {
23:
24: private static int[] first = { 3, 4, 8, 10 }; // sum=25
25: private static int[] second = { 6, 2, 9, 15 }; // sum=32
26: // upper bound on final completion time is 25+32:
27: private static int sum = 57;
28: private static int m = first.length;
29:
30: private static Set<Integer> setOfAllItems = new HashSet<Integer>();
31:
32: static{
33: setOfAllItems.add(0);
34: setOfAllItems.add(1);
35: setOfAllItems.add(2);
36: setOfAllItems.add(3);
37: }
38:
39: private static int fct(int t, int d) {
40: return Math.max(t - first[d], 0) + second[d];
41: }
42:
43: public static double f(Set<Integer> set, int t){
44: if(set.isEmpty())
45: return t;
46: double min = Double.MAX_VALUE;
47: for(int d : set){
48: Set<Integer> tmpSet = copySet(set);
49: tmpSet.remove(d);
50: double tmp = first[d]+f(tmpSet,fct(t,d));
51: if(tmp<min){
52: min=tmp;
53: }
54: }
55: return min;
56: }
57:
58: private static Set<Integer> copySet(Set<Integer> set) {
59: Set<Integer> s = new HashSet<Integer>();
60: for(int x : set){
61: s.add(x);
62: }
63: return s;
64: }
65:
66: /**
67: * @param args
68: */
69: public static void main(String[] args) {
70: System.out.println(f(setOfAllItems,0));
71: }
72:
73: }
posted on 2014-06-03 19:24 changedi 閱讀(1525) 評論(0) 編輯 收藏 所屬分類: 算法