// 01背包问题 一维优化
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int v[N], w[N], f[N];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> v[i] >> w[i];
for (int i = 1; i <= n; i++) {
for (int j = m; j >= v[i]; j--) {
f[j] = max(f[j], f[j - v[i]] + w[i]);
// 朴素:f[i][j] = max(f[i - 1][j], f[i - 1][j - v[i]] + w[i])
}
}
cout << f[m] << endl;
}
// 完全背包问题 最终版
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1010;
int v[N], w[N], f[N];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) cin >> v[i] >> w[i];
for (int i = 1; i <= n; i++) {
for (int j = v[i]; j <= m; j++) {
f[j] = max(f[j], f[j - v[i]] + w[i]);
// 朴素:f[i][j] = max(f[i - 1][j], f[i][j - v[i]] + w[i])
}
}
cout << f[m] << endl;
}
// 多重背包问题 朴素做法
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int v[N], w[N], s[N];
int f[N][N];
int main() {
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++) {
cin >> v[i] >> w[i] >> s[i];
}
// 三重循环
for (int i = 1; i <= n; i++) {
for (int j = 0; j <= m; j++) {
for (int k = 0; k <= s[i] && k * v[i] <= j; k++) {
f[i][j] = max(f[i][j], f[i - 1][j - k * v[i]] + k * w[i]);
}
}
}
cout << f[n][m] << endl;
return 0;
}
// 多重背包问题II 利用二进制思想优化
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 25000;
int v[N], w[N],f[N];
int main() {
int n, m;
cin >> n >> m;
// 核心是划分s[i],然后对所有划分出来的数用01背包思想
// 20: 1 2 4 8 5
int cnt = 0;
for (int i = 1; i <= n; i ++) {
int a, b, s;
cin >> a >> b >> s;
int k = 1;
while(k <= s) {
cnt ++;
v[cnt] = a * k;
w[cnt] = b * k;
s -= k;
k *= 2;
}
if (s > 0) {
cnt ++;
v[cnt] = a * s;
w[cnt] = b * s;
}
}
n = cnt;
// 01背包模板
for (int i = 1; i <= n; i ++) {
for (int j = m; j >= v[i]; j --) {
f[j] = max(f[j], f[j - v[i]] + w[i]);
}
}
cout << f[m] << endl;
return 0;
}
// 分组背包问题
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int v[N][N], w[N][N];
int f[N];
int s[N];
int n, m;
int main() {
cin >> n >>m ;
for (int i = 1; i <= n; i++) {
cin >> s[i];
for (int j = 1; j <= s[i]; j++) {
cin >> v[i][j] >> w[i][j];
}
}
// 01背包+每组选一种
/*
j逆序是因为 f[j] = max(f[j], f[j - v[i][k]] + w[i][k])
等价变形是 f[i][j] = max(f[i - 1][j], f[i - 1][j - v[i][k]] + w[i][k])
*/
for (int i = 1; i <= n; i++) {
for (int j = m; j >= 0; j--) {
for (int k = 1; k <= s[i]; k++) {
if (j >= v[i][k])
f[j] = max(f[j], f[j - v[i][k]] + w[i][k]);
}
}
}
cout << f[m] << endl;
return 0;
}