Hdu2159 dual full backpack

Source: Internet
Author: User

Different from a general backpack, an item selection restriction is added. Therefore, you need to add one dimension.

DP [I] [J] [k] indicates the first I items. Select J items and put them in a backpack with K capacity to obtain the maximum value.

Here, like a one-dimensional backpack, you can use a rolling array to omit one-dimensional

DP [I] [J] indicates the maximum value that a backpack with the size of J can obtain.

DP [I, j] = max (DP [I, j], DP [I-1] [J-W [k] + V [k]);

 

 1 #include <cstdio> 2 #include <cstring> 3 #include <string> 4 #include <algorithm> 5 #include <iostream> 6 using namespace std; 7 #define INF 0x3fffffff 8 const int maxn = 105; 9 const int maxv = 105;10 int dp[maxv][maxn],w[maxn],v[maxn];11 int main()12 {13    //freopen("in.txt","r",stdin);14     int n,m,k,s;15     while(cin>>n>>m>>k>>s)16     {17         for(int i = 1;i<=k;++i)18             scanf("%d%d",v+i,w+i);19         memset(dp,0,sizeof(dp));20         int flag = 0,ans = -1;21         for(int j = 0;j<=m;++j)22         {23             for(int i = 1;i<=s;++i)24             {25                 for(int x = 1;x<=k;++x)26                     if(j>=w[x]){27                             dp[i][j] = max(dp[i][j],dp[i-1][j-w[x]]+v[x]);28                             if(dp[i][j]>=n){flag = 1;ans = j;break;}29                     }30                 if(flag)break;31             }32             if(flag)break;33         }34         if(flag)printf("%d\n",m-ans);35         else puts("-1");36     }37     return 0;38 }

 

Hdu2159 dual full backpack

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.