多重揹包二進位制優化分析
阿新 • • 發佈:2018-11-25
列出一個模板供參考:
#include<bits/stdc++.h> #include<time.h> #define INF 0x3f3f3f3f using namespace std; #define N 1000 #define M 100000000 int m[N],c[N],w[N],f[M]; int V; int max(int a,int b){return a>b?a:b;} void ZeroOnePack(int cost,int weight){ int v; for(v=V;v>=cost;v--) f[v]=max(f[v],f[v-cost]+weight); } void CompletePack(int cost,int weight){ int v; for(v=cost;v<=V;v++) f[v]=max(f[v],f[v-cost]+weight); } void MultiplePack(int cost,int weight,int amount){ int k; if(cost*amount>=V){ CompletePack(cost,weight); return; } k=1; while(k<amount){ ZeroOnePack(k*cost,k*weight); amount=amount-k; k=k*2; } ZeroOnePack(amount*cost,amount*weight); } int main() { int n,i; scanf("%d %d",&n,&V); for(i=0;i<n;i++) scanf("%d %d %d",&m[i],&c[i],&w[i]); for(i=0;i<n;i++) MultiplePack(c[i],w[i],m[i]); printf("%d\n",f[V]); return 0; }