hdu2191 — 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活 (多重背包)

来源:互联网 发布:淘宝买家黑名单 编辑:程序博客网 时间:2024/06/05 10:39

题目大意:一共有资金n元,而市场有m种大米,每种大米都是袋装产品,其价格不等,并且只能整袋购买。问用有限的资金最多能采购多少公斤粮食。


思路分析:将多重背包问题转化为01背包,两种转化方法均不会超时,状态转移方程为 dp [ j ] = max ( dp [ j ] , dp [ j - p2 [ i ] ] + h2 [ i ] (j : n to p2[ i ] ),

两种方法的代码都贴上以供参考


<span style="font-size:14px;"><span style="color:#ff0000;">//时间复杂度为O(V N ΣlogMi)</span>#include <iostream>#include <algorithm>using namespace std;int p[2005];int h[2005];int dp[105];int main(){    int t;    cin>>t;    while(t--){        int n,m;        cin>>n>>m;        int coun=0;        fill(dp,dp+105,0);        for(int i=1;i<=m;i++){            int a,b,c,j,k=1;            cin>>a>>b>>c;            for(j=1;j<=c;j<<=1){                p[k+coun]=a*j;                h[k+coun]=b*j;                k++;                c-=j;            }            p[k+coun]=c*a;            h[k+coun]=c*b;            coun+=k;        }        for(int i=1;i<=coun;i++){            for(int j=n;j>=p[i];j--)                dp[j]=max(dp[j],dp[j-p[i]]+h[i]);        }        cout<<dp[n]<<endl;    }    return 0;}</span>


<span style="color:#ff0000;">//时间复杂度为 O(V N ΣMi)</span>#include <iostream>#include <algorithm>using namespace std;int p[2005];int h[2005];int dp[105];int main(){    int t;    cin>>t;    while(t--){        int n,m;        cin>>n>>m;        int coun=0;        fill(dp,dp+105,0);        for(int i=1;i<=m;i++){            int a,b,c;            cin>>a>>b>>c;            for(int j=1;j<=c;j++){                p[j+coun]=a;                h[j+coun]=b;            }            coun+=c;        }        for(int i=1;i<=coun;i++){            for(int j=n;j>=p[i];j--)                dp[j]=max(dp[j],dp[j-p[i]]+h[i]);        }        cout<<dp[n]<<endl;    }    return 0;}


0 0
原创粉丝点击