#include <iostream>
#include <cmath>
#define N 1005
using namespace std;
int n, m;
int f[N][N];
int v[N], w[N];
int main()
{
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 = 1; j <= m; j++)
{
if(j<v[i])
f[i][j] = f[i-1][j];
else
{
f[i][j] = max(f[i-1][j],f[i - 1][j-v[i]] + w[i]);
}
}
}
cout << f[n][m] << endl;
return 0;
}
这段代码我照着视频敲的,能正常输出,但我下面自己敲了一个一模一样的,不能输出。
#include <iostream>
#include <cmath>
#define NUM 1005
using namespace std;
int n, m;
int v[NUM], w[NUM];
int dp[NUM][NUM];
int main() {
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 = 1; j <= m; i++) {
if (j < v[i])
dp[i][j] = dp[i - 1][j];
else {
dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - v[i]] + w[i]);
}
}
}
cout << dp[n][m] << endl;
return 0;
}