T1267-01背包问题
时间限制: 1Sec 内存限制: 128MB 提交: 759 解决: 294
样例输入
10 4
2 1
3 3
4 5
7 9
样例输出
12
解法一:
#include<iostream>
#include <cstdio>
//0/1 背包问题
using namespace std;
int dp[35][205];
int w[35];
int c[205];
int main() {
int m, n;
cin >> m >> n;
for (int i = 1;i <= n;i++) {
cin >> w[i] >> c[i];
}
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 - 1][j - w[i]] + c[i]);
}
}
cout << dp[n][m];
return 0;
}
解法二:更优
#include <iostream>
using namespace std;
int dp[205];
int w[35];
int c[205];
int main(){
int m, n;
cin >> m >> n;
for (int i = 1;i <= n;i++) {
cin >> w[i] >> c[i];
}
for (int i = 1;i <= n;i++) {
for (int j = m;j >= 1;j--) {//递归从后面开始
if (j >= w[i])
dp[j] = max(dp[j], dp[j - w[i]] + c[i]);
}
}
cout << dp[m];
return 0;
}