本题完全模仿《背包问题九讲》。一会儿去好好学习下背包问题。注明一点,cost和weight是一样的,可以省略一个参数和一个数组(我没省)。不能多说了。贴上我微弱的代码:
1: #include <iostream>
2: #include <algorithm>
3: #include <memory.h>
4: using namespace std;
5: const int CASH_SIZE = 100001;
6: const int D_SIZE = 1001;
7: int volume;
8: int f[CASH_SIZE], costArr[D_SIZE], weightArr[D_SIZE], amountArr[D_SIZE];
9:
10: void ZeroOnePack(int cost, int weight)
11: {
12: for (int v=volume; v>=cost; v--)
13: f[v]=max(f[v], f[v-cost]+weight);
14: }
15:
16: void CompletePack(int cost, int weight, int i)
17: {
18: for (int v=cost; v<=volume; v++)
19: f[v]=max(f[v],f[v-costArr[i]]+weightArr[i]);
20: }
21:
22: void MultiplePack(int cost, int weight, int amount, int i)
23: {
24: if (cost*amount>=volume)
25: {
26: CompletePack(cost, weight, i);
27: return;
28: }
29: int k=1;
30: while (k<amount)
31: {
32: ZeroOnePack(k*cost, k*weight);
33: amount -= k;
34: k <<= 1;
35: }
36: ZeroOnePack(amount*cost, amount*weight);
37: }
38:
39: int main()
40: {
41: int n=0;
42: while (cin >> volume >> n)
43: {
44: memset(f, 0, sizeof(f));
45: memset(weightArr, 0, sizeof(weightArr));
46: memset(costArr, 0, sizeof(costArr));
47: for (int i=0; i<n; i++)
48: {
49: cin >> amountArr[i] >> costArr[i];
50: weightArr[i] = costArr[i];
51: }
52: for (int i=0; i<n; i++)
53: {
54: MultiplePack(costArr[i], weightArr[i], amountArr[i], i);
55: }
56: cout << f[volume] << endl;
57: }
58: return 0;
59: }