1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <algorithm> 5 using namespace std; 6 7 const int MAXN=1005; 8 int w[MAXN],v[MAXN]; //代表第i个物品的重量,和价值 9 10 int N,W; //分别代表物品的个数,和包可以装的总物品重量 11 int dp[MAXN][MAXN]; 12 13 //穷竭搜索解决 14 int dfs(int i,int j){ 15 if(i==N) 16 return 0; 17 int res=-10000; 18 if(w[i]>j){ 19 res=dfs(i+1,j); 20 }else{ 21 for(int k=0;k*w[i]<=j;k++){ 22 res=max(res,dfs(i+1,j-k*w[i])+k*v[i]); 23 } 24 } 25 return res; 26 } 27 28 //记忆化搜索解决 29 int mdfs(int i,int j){ 30 if(i==N) 31 return 0; 32 if(dp[i][j]!=-1) 33 return dp[i][j]; 34 int res=-1000; 35 if(w[i]>j){ 36 res=mdfs(i+1,j); 37 }else{ 38 for(int k=0;k*w[i]<=j;k++){ 39 res=max(res,mdfs(i+1,j-k*w[i])+k*v[i]); 40 } 41 } 42 return dp[i][j]=res; 43 } 44 45 //DP解决 O(NW^2) 46 int DP(){ 47 memset(dp,0,sizeof(dp)); 48 for(int i=0;i<N;i++){ 49 for(int j=0;j<=W;j++){ 50 for(int k=0;k*w[i]<=j;k++){ 51 dp[i+1][j]=max(dp[i+1][j],dp[i][j-k*w[i]]+k*v[i]); 52 } 53 } 54 } 55 return dp[N][W]; 56 } 57 //DP解决 O(NW) 58 int DP2(){ 59 memset(dp,0,sizeof(dp)); 60 for(int i=0;i<N;i++) 61 for(int j=0;j<=W;j++) 62 if(w[i]<=j) 63 dp[i+1][j]=max(dp[i][j],dp[i+1][j-w[i]]+v[i]); 64 else dp[i+1][j]=dp[i][j]; 65 return dp[N][W]; 66 } 67 int main(){ 68 cin>>N>>W; 69 for(int i=0;i<N;i++){ 70 cin>>w[i]>>v[i]; 71 } 72 cout<<dfs(0,W)<<endl; 73 memset(dp,-1,sizeof(dp)); 74 cout<<mdfs(0,W)<<endl; 75 cout<<DP()<<endl; 76 cout<<DP2()<<endl; 77 }