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 long 20 #define inf 0x7f7f7f7f 21 #define lc l,m,rt<<1 22 #define rc m + 1,r,rt<<1|1 23 #define pi acos(-1.0) 24 25 #define L(x) (x) << 1 26 #define R(x) (x) << 1 | 1 27 #define MID(l, r) (l + r) >> 1 28 #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 1000000000 37 #define N 100010 38 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 }
时间: 2024-11-01 15:50:11