solution1
二维形式
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 35, maxv = 210;
int w[maxn], c[maxn], dp[maxn][maxv];
int main(){
int n, m;
scanf("%d%d", &m, &n);
for(int i = 1; i <= n; i++){
scanf("%d%d", &w[i], &c[i]);
}
for(int i = 0; i <= m; i++){//边界
dp[0][i] = 0;
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(j < w[i]) dp[i][j] = dp[i - 1][j];
else dp[i][j] = max(dp[i - 1][j], dp[i][j - w[i]] + c[i]);
}
}
printf("max=%d", dp[n][m]);
return 0;
}
solution2
一维形式
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn = 35, maxv = 210;
int w[maxn], c[maxn], dp[maxv];
int main(){
int n, m;
scanf("%d%d", &m, &n);
for(int i = 1; i <= n; i++){
scanf("%d%d", &w[i], &c[i]);
}
for(int i = 0; i <= m; i++){//边界
dp[i] = 0;
}
for(int i = 1; i <= n; i++){//状态转移方程
for(int j = w[i]; j <= m; j++){//必须正序
dp[j] = max(dp[j], dp[j - w[i]] + c[i]);
}
}
printf("max=%d", dp[m]);
return 0;
}