NOIP2005采药
这题比较简单,一看就知道是01背包问题,(但是注意第一行的输入和原题换了个位置),直接写模板即可
C++ 代码
#include <iostream>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N], f[N][N];
int main() {
cin >> m >> n;
for (int i = 1; i <= n; i ++ ) cin >> v[i] >> w[i];
for (int i = 1; i <= n; i ++ ) {
for (int j = 0; j <= m; j ++ ) {
f[i][j] = f[i - 1][j];
if (j >= v[i]) f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + w[i]);
}
}
cout << f[n][m];
return 0;
}
或者写一维数组的优化版
感兴趣的话点个赞或关注我~