正常二维dp
#include<bits/stdc++.h>
using namespace std;
const int N = 1117;
int f[N][N], n, V, v[N], w[N];
int main()
{
cin >> n >> V;
for(int i = 1; i <= n; i ++)cin >> v[i] >> w[i];
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= V; j ++)
f[i][j] = max(f[i-1][j], (f[i-1][j-v[i]] + w[i]) * (j >= v[i]));
cout << f[n][V];
}
边输入边处理
#include<bits/stdc++.h>
using namespace std;
const int N = 1117;
int f[N][N], n, V, v, w;
int main()
{
cin >> n >> V;
for(int i = 1; i <= n; i ++)
{
cin >> v >> w;
for(int j = 1; j <= V; j ++)
f[i][j] = max(f[i-1][j], (f[i-1][j-v] + w) * (j >= v));
}
cout << f[n][V];
}
滚动数组
#include<bits/stdc++.h>
using namespace std;
const int N = 1117;
int f[2][N], n, V, v, w, t;
int main()
{
cin >> n >> V;
for(int i = 1; i <= n; i ++)
{
cin >> v >> w;
for(int j = 1; j <= V; j ++)
f[t][j] = max(f[t^1][j], (f[t^1][j-v] + w) * (j >= v));
t ^= 1;
}
cout << f[t^1][V];
}
一维数组没有滚动数组好理解,不好debug并且优化不多,建议写到滚动数组结束