把多重背包的优化方式写了一个合集
C++ 代码
#include<bits/stdc++.h>
using namespace std;
const int N = 6010;
int f[N] , g[N];
int v , w , s;
int n , m;
struct kp{
int v , w;
};
int q[N] , tt = -1 , hh = 0;
void pusu(){
for(int i = 1 ;i <= n;i++){
cin>>v>>w>>s;
for(int j=m ; j >= 0;j--)
for(int k = 1 ; k <= s ; k++)
if(j >= k*v ) f[j] = max(f[j] , f[j - k*v] + k*w);
}
}
void erjinzhi(){
vector<kp> mp;
for(int i=1 ; i<=n ; i++) {
cin>>v>>w>>s;
int k = 1;
while(s>=k){
mp.push_back({k*v , k*w});
s -= k;
k*=2;
}
if(s>0) mp.push_back({s*v , s*w});
}
for(int i=0;i<mp.size();i++)
for(int j = m; j >= 0 ;j--)
if(j >= mp[i].v ) f[j] = max(f[j] , f[j-mp[i].v] + mp[i].w);
}
int dequeue_you(){
for(int i = 1 ;i <=n ;i++){
cin>>v>>w>>s;
memcpy( g , f, sizeof f);
for(int j = 0 ; j < v ; j++){
hh = 0 , tt = -1;
for(int k = j ; k <= m ; k += v){
if(hh<=tt && k - q[hh] > s*v) hh++ ;
while(hh <= tt && g[q[tt]] + (k-q[tt])/v * w <= g[k] ) tt--;
q[++tt] = k;
f[k] = g[q[hh]] + (k - q[hh])/v * w;
}
}
}
}
int main(){
cin>>n>>m;
dequeue_you();
cout<<f[m]<<endl;
}
good
好活