叠箱子问题 之 动态规划

/*
叠箱子问题:
	dp[i][j] := 第i个箱子到第n个箱子叠放起来总重量为j,所能叠放的最多箱子数
	dp[i][j] = max(dp[i][j], dp[i+1][j - weight[i]] + 1)
*/
 1 #include <iostream>
 2 #include <fstream>
 3 #include <sstream>
 4 #include <cstdlib>
 5 #include <cstdio>
 6 #include <cstddef>
 7 #include <iterator>
 8 #include <algorithm>
 9 #include <string>
10 #include <locale>
11 #include <cmath>
12 #include <vector>
13 #include <cstring>
14 #include <map>
15 #include <utility>
16 #include <queue>
17 #include <stack>
18 #include <set>
19 #include <functional>
20 using namespace std;
21 typedef pair<int, int> PII;
22 typedef long long int64;
23 const int INF = 0x3f3f3f3f;
24 const int modPrime = 3046721;
25 const double eps = 1e-9;
26 const int MaxN = 100010;
27 const int MaxM = 30;
28 const char Opt[4] = { '+', '-', '*', '/' };
29 
30 int dp[6010];
31 /*
32 pW:  从1号到n号的自身重量(1 <= Wn <= 3000)
33 pM: 从1号到n号的可承受重量(1 <= Mn <= 3000)
34 返回值: 一次所能叠放的最多箱子数
35 */
36 int CalcMaxNum(int n, int * pW, int * pM)
37 {
38     if ((n < 1) || (n > 900) || (NULL == pW) || (NULL == pM))
39     {
40         return 0;
41     }
42 
43     int maxTotalWeight = 6000;
44     fill(dp, dp + maxTotalWeight + 1, 0);
45 
46     for (int i = n - 1; i >= 0; --i)
47     {
48         for (int j = maxTotalWeight; j >= 0; --j)
49         {
50             if ((j >= pW[i]) && (j - pW[i] <= pM[i]))
51             {
52                 dp[j] = max(dp[j], dp[j - pW[i]] + 1);
53             }
54         }
55     }
56     int ans = *max_element(dp, dp + maxTotalWeight + 1);
57     return ans;
58 }
59 
60 
61 
62 int main()
63 {
64 #ifdef HOME
65     freopen("in", "r", stdin);
66     //freopen("out", "w", stdout);
67 #endif
68 
69     int ws[] = {
70         19, 7, 5, 6, 1 };
71     int ms[] = {
72         15, 13, 7, 8, 2 };
73     int ret = CalcMaxNum(5,
74         ws,
75         ms);
76     (ret == 4);
77 
78 #ifdef HOME
79     cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl;
80     _CrtDumpMemoryLeaks();
81 #endif
82     return 0;
83 }

 

 
posted @ 2016-01-17 23:49  JmingS  阅读(1054)  评论(0编辑  收藏  举报