-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuva-10130.cpp
90 lines (70 loc) · 1.92 KB
/
uva-10130.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <bits/stdc++.h>
#define MAX_ITEM 1000
#define MAX_PEOPLE 100
#define MAX_WEIGHT 30
using namespace std;
int n;
int price[MAX_ITEM + 1];
int weight[MAX_ITEM + 1];
int capacity[MAX_PEOPLE + 1];
int DP[MAX_ITEM + 1][MAX_WEIGHT + 1];
int DP2[MAX_WEIGHT + 1]; /// to save maximum profit for a distinct capacity
void init();
int maxProfit(int personNo, int itemNo, int takenWeight);
int main()
{
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
int test, i, j, k, g, total, cap;
scanf("%d", &test);
while (test--) {
scanf("%d", &n);
for (i = 1; i <= n; i++) {
scanf("%d%d", &price[i], &weight[i]);
}
scanf("%d", &g);
for (i = 1; i <= g; i++) {
scanf("%d", &capacity[i]);
}
for (i = 0; i <= MAX_WEIGHT; i++) {
DP2[i] = -1;
}
total = 0;
for (k = 1; k <= g; k++) {
init();
cap = capacity[k];
if (DP2[cap] == -1) {
DP2[cap] = maxProfit(k, 1, 0);
}
total += DP2[cap];
}
printf("%d\n", total);
}
return 0;
}
void init()
{
for (int i = 0; i <= MAX_ITEM; i++) {
for (int j = 0; j <= MAX_WEIGHT; j++) {
DP[i][j] = 0;
}
}
}
int maxProfit(int personNo, int itemNo, int takenWeight)
{
if (itemNo > n) {
return 0;
}
else if (DP[itemNo][takenWeight] != 0) {
return DP[itemNo][takenWeight];
}
int profit1, profit2;
if (takenWeight + weight[itemNo] <= capacity[personNo]) {
profit1 = price[itemNo] + maxProfit(personNo, itemNo + 1, takenWeight + weight[itemNo]);
}
else {
profit1 = 0;
}
profit2 = maxProfit(personNo, itemNo + 1, takenWeight);
return (DP[itemNo][takenWeight] = max(profit1, profit2));
}