-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathpunch.cpp
89 lines (77 loc) · 1.96 KB
/
punch.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
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
// Value
struct value {
int cost;
int numBeverages;
bool usesBeverage;
// "lexicographic" order with the following priorities:
// 1. Cheapest
// 2. Highest number of beverages
// 3. Not needing to take the drink
bool operator>(value v) {
return cost < v.cost ||
(cost == v.cost && numBeverages > v.numBeverages) ||
(cost == v.cost && numBeverages == v.numBeverages && !usesBeverage && v.usesBeverage);
}
};
// Super similar to the knapsack problem
// => Solve with DP
void solve()
{
int n, k;
cin >> n >> k;
// Read costs and volumes
vector<int> c(n);
vector<int> v(n);
for (int i = 0; i < n; ++i) {
cin >> c[i] >> v[i];
}
// Initialize DP
// row i: all beverages up to i available
// col j: at least j liters needed
vector<vector<value>> dp(n, vector<value>(k + 1));
for (int i = 1; i < n; ++i) {
dp[i][0] = {0, 0, false};
}
for (int j = 1; j <= k; ++j) {
int cost = c[0] * int(ceil(1. * j / v[0]));
dp[0][j] = {cost, 1, true};
}
for (int i = 1; i < n; ++i) {
for (int j = 1; j <= k; ++j) {
// Value with i - 1 beverages
value valueWithout = dp[i - 1][j];
valueWithout.usesBeverage = false;
// Value with beverage i
value valueWith = {c[i], 1, true};
// More than one bottle needed
if (j > v[i]) {
valueWith.cost += dp[i][j - v[i]].cost;
valueWith.numBeverages = dp[i][j - v[i]].numBeverages;
if (!dp[i][j - v[i]].usesBeverage) {
valueWith.numBeverages += 1;
}
}
// What is better?
if (valueWithout > valueWith) {
dp[i][j] = valueWithout;
}
else {
dp[i][j] = valueWith;
}
}
}
// Print solution
cout << dp[n - 1][k].cost << " " << dp[n - 1][k].numBeverages << endl;
}
int main() {
ios_base::sync_with_stdio(false);
int t; cin >> t;
while (t--) {
solve();
}
return 0;
}