基礎01背包問題

來源:互聯網
上載者:User

標籤:

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1085

http://hihocoder.com/problemset/problem/1038?sid=320857

在N件物品取出若干件放在容量為W的背包裡,每件物品的體積為W1,W2……Wn(Wi為整數),與之相對應的價值為P1,P2……Pn(Pi為整數)。求背包能夠容納的最大價值。

動態轉移方程    dp[i][j]=max(dp[i-1][j],dp[i-1][j-v[i]]+w[i]);  

背包九講裡面講的很好。

 1 #include <iostream> 2 #include <cstdio> 3 #include <cmath> 4 #include <vector> 5 #include <cstring> 6 #include <string> 7 #include <algorithm> 8 #include <string> 9 #include <set>10 #include <functional>11 #include <numeric>12 #include <sstream>13 #include <stack>14 #include <map>15 #include <queue>16 17 #define CL(arr, val)    memset(arr, val, sizeof(arr))18 19 #define ll long long20 #define inf 0x7f7f7f7f21 #define lc l,m,rt<<122 #define rc m + 1,r,rt<<1|123 #define pi acos(-1.0)24 25 #define L(x)    (x) << 126 #define R(x)    (x) << 1 | 127 #define MID(l, r)   (l + r) >> 128 #define Min(x, y)   (x) < (y) ? (x) : (y)29 #define Max(x, y)   (x) < (y) ? (y) : (x)30 #define E(x)        (1 << (x))31 #define iabs(x)     (x) < 0 ? -(x) : (x)32 #define OUT(x)  printf("%I64d\n", x)33 #define lowbit(x)   (x)&(-x)34 #define Read()  freopen("a.txt", "r", stdin)35 #define Write() freopen("b.txt", "w", stdout);36 #define maxn 100000000037 #define N 10001038 using namespace std;39 40 int n,m;41 int f[N];42 void ZeroOnePack(int cost,int weight)43 {44     for(int v=m;v>=cost;v--)45         f[v]=max(f[v],f[v-cost]+weight);46 }47 int main()48 {49    //Read();50    //Write();51    int a,b;52     while(~scanf("%d%d",&n,&m))53     {54         memset(f,0,sizeof(f));55         for(int i=0;i<n;i++)56         {57             scanf("%d%d",&a,&b);58             ZeroOnePack(a,b);59         }60         printf("%d\n",f[m]);61     }62     return 0;63 }

 

基礎01背包問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.