关注微信公众号 CodeFun 更多题解
思路
状态转移方程如下:
- d p [ i + 1 ] [ j ] dp[i+1][j] dp[i+1][j]从0到i这i+1个物品中选出总重量不超过j的物品时总价值的最大值
- d p [ 0 ] [ j ] = 0 dp[0][j]=0 dp[0][j]=0
d p [ i + 1 ] [ j ] = { d p [ i ] [ j ] ( j < v [ i ] ) max ( d p [ i ] [ j ] , d p [ i ] [ j − v [ i ] ] + v [ i ] × w [ i ] ) dp[i+1][j]=\left\{\begin{array}{ll} {d p[i][j]} & {(j<v[i])} \\ {\max (d p[i][j], d p[i][j-v[i]]+v[i]\times w[i] )} & {} \end{array}\right. dp[i+1][j]={dp[i][j]max(dp[i][j],dp[i][j−v[i]]+v[i]×w[i])(j<v[i])
code
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll dp[30][30010];
int v[30],w[30];
int main(){
int n,m;
cin>>n>>m;
for(int i=0;i<m;i++) cin>>v[i]>>w[i];
for(int i=0;i<m;i++)
for(int j=0;j<=n;j++){
if(j<v[i]) dp[i+1][j]=dp[i][j];
else dp[i+1][j]=max(dp[i][j],dp[i][j-v[i]]+v[i]*w[i]);
}
cout<<dp[m][n]<<endl;
return 0;
}