输入样例
3 5
2
1 2
2 4
1
3 4
1
4 5
输出样例:
8
二维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int v[N][N], w[N][N], f[N][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];
}
}
for(int i = 1; i <= n; i ++ ){
for(int j = 0; j <= m; j ++ ){
for(int k = 0; k <= s[i]; k ++ ){
if(j >= v[i][k]){
f[i][j] = max(f[i][j], f[i - 1][j - v[i][k]] + w[i][k]);
}
}
}
}
cout << f[n][m] << endl;
return 0;
}
一维
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int v[N][N], w[N][N], 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];
}
}
for(int i = 1; i <= n; i ++ ){
for(int j = m; j >= 0; j -- ){
for(int k = 0; 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;
}