多重背包问题 I
https://www.acwing.com/problem/content/4/
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<queue>
#include<stack>
#include<cstring>
#include<unordered_map>
using namespace std;
typedef long long LL;
int N,V;
int v[105],w[105],s[105];
int f[105][105];
int main(){
cin>>N>>V;
for(int i=1;i<=N;i++){
cin>>v[i]>>w[i]>>s[i];
}
for(int i=1;i<=N;i++){
for(int j=0;j<=V;j++){
for(int k=0;k<=s[i];k++){
if(j>=k*v[i]){
f[i][j]=max(f[i][j],f[i-1][j-k*v[i]]+k*w[i]);
}
}
}
}
cout<<f[N][V];
return 0;
}
// freopen("testdata.in", "r", stdin);
多重背包问题 II
https://www.acwing.com/problem/content/5/
转化成01背包问题,同时划分背包时不一个个分,而是通过2的次方数拆分
这样也可以表示出1到n的所有数
#include <iostream>
#include<algorithm>
#include<cstdio>
#include<vector>
#include<queue>
#include<stack>
#include<cstring>
using namespace std;
int N,V;
struct Good{
int v,w;
};
vector<Good> goods;
int v,w,s;
int dp[2005];
int main(){
cin>>N>>V;
while(N--){
cin>>v>>w>>s;
for(int k=1;k<=s;k*=2){
s-=k;
goods.push_back({k*v,k*w});
}
if(s>0){
goods.push_back({s*v,s*w});
}
}
for(auto g:goods){
for(int j=V;j>=g.v;j--){
dp[j]=max(dp[j],dp[j-g.v]+g.w);
}
}
cout<<dp[V];
return 0;
}
// freopen("testdata.in", "r", stdin);
分组背包问题
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 110;
int n, m;
int v[N][N], w[N][N], s[N];
int f[N];
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
{
cin >> s[i];
for (int j = 0; j < s[i]; j ++ )
cin >> v[i][j] >> w[i][j];
}
for (int i = 1; i <= n; i ++ )
for (int j = m; j >= 0; j -- )
for (int k = 0; k < s[i]; k ++ )
if (v[i][k] <= j)
f[j] = max(f[j], f[j - v[i][k]] + w[i][k]);
cout << f[m] << endl;
return 0;
}