poj 1276 多重背包
生活随笔
收集整理的這篇文章主要介紹了
poj 1276 多重背包
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
735 3 4 125 6 5 3 350 //735的最大額,3種,4個125,6個5,3個350
633 4 500 30 6 100 1 5 0 1
735 0
0 3 10 100 10 50 10 10
735 630 0 0 1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 #include<queue> 7 using namespace std; 8 const int maxn=100005; 9 int n,m,t; 10 int dp[maxn],w[maxn],v[maxn]; 11 int nValue; 12 //0-1背包,代價為cost,獲得的價值為weight 13 void ZeroOnePack(int cost,int weight) 14 { 15 for(int i=nValue;i>=cost;i--) 16 dp[i]=max(dp[i],dp[i-cost]+weight); 17 } 18 19 //完全背包,代價為cost,獲得的價值為weight 20 void CompletePack(int cost,int weight) 21 { 22 for(int i=cost;i<=nValue;i++) 23 dp[i]=max(dp[i],dp[i-cost]+weight); 24 } 25 26 //多重背包 27 void MultiplePack(int cost,int weight,int amount) 28 { 29 if(cost*amount>=nValue) CompletePack(cost,weight); 30 else 31 { 32 int k=1; 33 while(k<amount) 34 { 35 ZeroOnePack(k*cost,k*weight); 36 amount-=k; 37 k<<=1; 38 } 39 ZeroOnePack(amount*cost,amount*weight);//這個不要忘記了,經常掉了 40 } 41 } 42 int main() 43 { 44 int i,j,k; 45 #ifndef ONLINE_JUDGE 46 freopen("1.in","r",stdin); 47 #endif 48 while(scanf("%d%d",&nValue,&n)!=EOF) 49 { 50 for(i=0;i<n;i++) 51 { 52 scanf("%d%d",&w[i],&v[i]); 53 } 54 memset(dp,0,sizeof(dp)); 55 for(i=0;i<n;i++) 56 { 57 MultiplePack(v[i],v[i],w[i]); 58 } 59 printf("%d\n",dp[nValue]); 60 } 61 }
735 630 0 0 1 #include<cstdio> 2 #include<iostream> 3 #include<algorithm> 4 #include<cstring> 5 #include<cmath> 6 #include<queue> 7 using namespace std; 8 const int maxn=100005; 9 int n,m,t; 10 int dp[maxn],w[maxn],v[maxn]; 11 int nValue; 12 //0-1背包,代價為cost,獲得的價值為weight 13 void ZeroOnePack(int cost,int weight) 14 { 15 for(int i=nValue;i>=cost;i--) 16 dp[i]=max(dp[i],dp[i-cost]+weight); 17 } 18 19 //完全背包,代價為cost,獲得的價值為weight 20 void CompletePack(int cost,int weight) 21 { 22 for(int i=cost;i<=nValue;i++) 23 dp[i]=max(dp[i],dp[i-cost]+weight); 24 } 25 26 //多重背包 27 void MultiplePack(int cost,int weight,int amount) 28 { 29 if(cost*amount>=nValue) CompletePack(cost,weight); 30 else 31 { 32 int k=1; 33 while(k<amount) 34 { 35 ZeroOnePack(k*cost,k*weight); 36 amount-=k; 37 k<<=1; 38 } 39 ZeroOnePack(amount*cost,amount*weight);//這個不要忘記了,經常掉了 40 } 41 } 42 int main() 43 { 44 int i,j,k; 45 #ifndef ONLINE_JUDGE 46 freopen("1.in","r",stdin); 47 #endif 48 while(scanf("%d%d",&nValue,&n)!=EOF) 49 { 50 for(i=0;i<n;i++) 51 { 52 scanf("%d%d",&w[i],&v[i]); 53 } 54 memset(dp,0,sizeof(dp)); 55 for(i=0;i<n;i++) 56 { 57 MultiplePack(v[i],v[i],w[i]); 58 } 59 printf("%d\n",dp[nValue]); 60 } 61 }
?
轉載于:https://www.cnblogs.com/cnblogs321114287/p/4356324.html
總結
以上是生活随笔為你收集整理的poj 1276 多重背包的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简练软考知识点整理-控制范围
- 下一篇: [BZOJ 3236] [Ahoi201