ProgramAlgTrain/20240919/CSP常考算法模板/背包问题_01.cpp

33 lines
778 B
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>
using namespace std;
const int maxm = 201, maxn = 31;
int m, n;
int w[maxn], c[maxn];
int f[maxn][maxm];
/*
10 4
2 1
3 3
4 5
7 9
*/
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cin>>m>>n; //背包容量m和物品数量n
for (int i = 1; i <= n; i++) //在初始化循环变量部分,定义一个变量并初始化
cin>>w[i]>>c[i]; //每个物品的重量和价值
for (int i = 1; i <= n; i++) // f[i][v]表示前i件物品总重量不超过v的最优价值
for (int v = m; v > 0; v--)
if (w[i] <= v)
f[i][v] = max(f[i-1][v],f[i-1][v-w[i]]+c[i]);
else
f[i][v] = f[i-1][v];
cout<<f[n][m]<<endl; // f[n][m]为最优解
return 0;
}