背包模板

来源:互联网 发布:淘宝助理5.7 编辑:程序博客网 时间:2024/06/05 14:06

0-1背包

#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespace std;const int MAX_NUM=1e5+10;const int MAX_WEIGHT=1e5+10;const int MAX=0x3f3f3f3f;int weight[MAX_NUM+50];int value[MAX_NUM+50];int dp[MAX_WEIGHT+50];int main(){    int T;    cin>>T;    while(T--)    {        memset(dp,0,sizeof(dp));        int n,w;        cin>>n>>w;        int i,j;        for(i=1;i<=n;i++)            cin>>weight[i]>>value[i];        for(i=1;i<=n;i++)        {            for(j=w;j>=weight[i];j--)            {                dp[j]=max(dp[j],dp[j-weight[i]]+value[i]);            }        }        cout<<dp[w]<<endl;    }}

完全背包:
1.求最大价值

#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespace std;const int MAX_NUM=1e5+10;const int MAX_WEIGHT=1e5+10;const int MAX=0x3f3f3f3f;int weight[MAX_NUM+50];int value[MAX_NUM+50];int dp[MAX_WEIGHT+50];int main(){    int T;    cin>>T;    while(T--)    {        memset(dp,0,sizeof(dp));//每次dp重新赋值为0        int n,w;        cin>>n>>w;        int i,j;        for(i=1;i<=n;i++)            cin>>weight[i]>>value[i];        for(i=1;i<=n;i++)        {            for(j=weight[i];j<=w;j++)//和0-1背包不同            {                dp[j]=max(dp[j],dp[j-weight[i]]+value[i]);            }        }        cout<<dp[w]<<endl;    }}

2.求最小价值

#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespace std;const int MAX_NUM=1e5+10;const int MAX_WEIGHT=1e5+10;const int MAX=0x3f3f3f3f;int weight[MAX_NUM+50];int value[MAX_NUM+50];int dp[MAX_WEIGHT+50];int main(){    int T;    cin>>T;    while(T--)    {        memset(dp,MAX,sizeof(dp));//每次重新赋值为最大值,并且dp[0]=0;        dp[0]=0;        int n,w;        cin>>n>>w;        int i,j;        for(i=1;i<=n;i++)            cin>>weight[i]>>value[i];        for(i=1;i<=n;i++)        {            for(j=weight[i];j<=w;j++)            {                dp[j]=min(dp[j],dp[j-weight[i]]+value[i]);            }        }        cout<<dp[w]<<endl;    }}

多重背包:

#include<iostream>#include<cstring>#include<cstdio>#include<algorithm>using namespace std;const int M=1e5+10;struct Rice{    int price;    int weight;} rice[M+50];int dp[M+50];int main(){    int T;    cin>>T;    while(T--)    {        memset(dp,0,sizeof(dp));        int n,w;        cin>>n>>w;        int index=0,i,j;        for(i=1; i<=n; i++)        {            int pri,wei,num;            cin>>pri>>wei>>num;            int k=1;            while(num-k>0)            {                num-=k;                rice[++index].price=pri*k;                rice[index].weight=wei*k;                k*=2;            }            rice[++index].price=pri*num;            rice[index].weight=wei*num;        }        for(i=1;i<=index;i++)        {            for(j=w;j>=rice[i].price;j--)            {                dp[j]=max(dp[j],dp[j-rice[i].weight]+rice[i].price);            }        }        cout<<dp[w]<<endl;    }}
原创粉丝点击