Files
python/TangDou/LanQiaoBei/LanQiao12GuoSai/GS12_4_ErWei.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

35 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}