You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
1.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
// https://www.acwing.com/solution/content/39331/
using namespace std;
const int N = 1010;
int n, m;
int v[N], w[N];
int f[N][N];
/**
测试用例:
80 2
18 10
30 20
体积大小n=80物品个数m=2
第一个物品 体积w[1]=18产生的价值v[1]=10
第二个物品 体积w[2]=30产生的价值v[2]=20
选择方法第一个物品选择1个第二个物品选择2个共10+20*2=50
*/
//完全背包问题
int main() {
cin >> m >> n; //n是物品种类m是背包上限本题是钱数
for (int i = 1; i <= n; i++) cin >> w[i] >> v[i];//注意这里的顺序,背包上限是钱,分清价格是重量,重量是价值,这里是反的
for (int i = 1; i <= n; i++) //考虑前i个物品
for (int j = 1; j <= m; j++) //从1开始到m去考虑重量下的最优解
//对比 LanQiao12ShengSai/BC4_ErWei_DP.cpp 01背包
if (j >= w[i]) f[i][j] = max(f[i][j], f[i][j - w[i]] + v[i]); //还可以在i中商品中选择注意01背包是f[i-1][j]
else f[i][j] = f[i - 1][j]; //不要这个物品
//输出结果
cout << f[n][m] << endl;
return 0;
}