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

21 lines
515 B
C++
Raw Normal View History

2024-09-19 02:22:41 +00:00
#include <bits/stdc++.h>
using namespace std;
const int maxm=2001,maxn=31;
int n,m,v,i;
int c[maxn],w[maxn];
int f[maxm];
int main()
{
2024-09-19 03:11:59 +00:00
scanf("%d%d",&m,&n); //背包容量m和物品数量n
2024-09-19 02:22:41 +00:00
for(i=1;i<=n;i++)
scanf("%d%d",&w[i],&c[i]);
for(i=1;i<=n;i++)
2024-09-19 03:11:59 +00:00
for(v=w[i];v<=m;v++) //设 f[v]表示重量不超过v公斤的最大价值
2024-09-19 02:22:41 +00:00
if(f[v-w[i]]+c[i]>f[v])
f[v]=f[v-w[i]]+c[i];
2024-09-19 03:11:59 +00:00
printf("max=%d\n",f[m]); // f[m]为最优解
2024-09-19 02:22:41 +00:00
return 0;
}