例题
OpenJudge - 采药
二维写法
#include <iostream>
using namespace std;
const int MAXN = 1010;
int f[MAXN][MAXN], w[MAXN], c[MAXN];
int main() {
int t, m;
cin >> t >> m;
for(int i=1; i<=m; i++)
cin >> w[i] >> c[i];
for(int i=1; i<=m; i++)
for(int j=1; j<=t; j++)
if(w[i]<=j)
f[i][j] = max(f[i-1][j], f[i-1][j-w[i]] + c[i]);
else
f[i][j] = f[i-1][j];
cout << f[m][t] << endl;
return 0;
}
维度压缩(一维)[tui]
#include <iostream>
using namespace std;
const int MAXN = 1010;
int f[MAXN], w[MAXN], c[MAXN];
int main() {
int t, m;
cin >> t >> m;
for(int i=1; i<=m; i++)
cin >> w[i] >> c[i];
for(int i=1;i<=m;i++)
for(int j=t;j>=w[i];j--)
f[j]=max(f[j],f[j-w[i]]+c[i]);
cout << f[t] << endl;
return 0;
}