HDU2159 二重完全背包

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   for   div   sp   log   

和普通的完全背包不同的地方時多了物品選取的限制,因此需要增加一維

dp[i][j][k]表示前i種物品,選取j個放入容量為k的背包中所能得到的最大價值

這裡和一維的背包一樣可以利用滾動數組省略一維即

dp[i][j] 表示前選取i個放入容量為j的背包所能得到的最大價值

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 二重完全背包

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.