一、题目链接
二、题目分析
(一)算法标签
背包问题 DP
(二)解题思路
三、AC代码
解法一(二维):
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
// f[i][j]表示从前i个物品中选,体积不超过j的最大价值
int f[N][N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
scanf("%d%d", &v[i], &w[i]);
for (int i = 1; i <= n; i ++ )
for (int j = 0; j <= m; j ++ )
{
// 不选第i件物品
f[i][j] = f[i - 1][j];
// 选第i件物品
if (j >= v[i]) f[i][j] = max(f[i][j], f[i - 1][j - v[i]] + w[i]);
}
cout << f[n][m] << endl;
return 0;
}
解法二(一维):
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
// f[j]表示体积不超过j的最大价值
int f[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
scanf("%d%d", &v[i], &w[i]);
for (int i = 1; i <= n; i ++ )
for (int j = m; j >= v[i]; j -- )
f[j] = max(f[j], f[j - v[i]] + w[i]);
cout << f[m] << endl;
return 0;
}
输入时DP:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010;
int n, m;
int v, w;
// f[j]表示体积不超过j的最大价值
int f[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
{
scanf("%d%d", &v, &w);
for (int j = m; j >= v; j -- )
f[j] = max(f[j], f[j - v] + w);
}
cout << f[m] << endl;
return 0;
}