一、引入
二、一维解法(推荐解法)
const int maxn=5E4+100;
int C[maxn],W[maxn];
int dp[maxn*4];
int V;
int main()
{
int n;
cin>>n>>V;
for(int i=1;i<=n;i++)
{
cin>>C[i]>>W[i];
}
memset(dp,0,sizeof(dp));
dp[0]=0;
for(int i=1;i<=n;i++)
for(int j=C[i];j<=V;j++)
dp[j]=max(dp[j],dp[j-C[i]]+W[i]);
cout<<dp[V]<<endl;
return 0;
}
三、二维解法
const int maxn=1E4+100;
int C[maxn],W[maxn];
int dp[maxn][maxn*4];
int V;
int main()
{
int n;
cin>>n>>V;
for(int i=1;i<=n;i++)
{
cin>>C[i]>>W[i];
}
memset(dp,0,sizeof(dp));
dp[0][0]=0;
for(int i=1;i<=n;i++)
for(int j=0;j<=V;j++)
{
if(j>=C[i])
dp[i][j]=max(dp[i-1][j],dp[i][j-C[i]]+W[i]);
else
dp[i][j]=dp[i-1][j];
}
cout<<dp[n][V]<<endl;
return 0;
}
四(附)、完全背包板子题
HDU1114
#include<bits/stdc++.h>
#define ll long long
#define INF 0x3f3f3f3f
#define EPS 1E-10
using namespace std;
const int maxn=5E4+100;
int C[maxn],W[maxn];
int dp[maxn*4];
int V;
int main()
{
int t;
cin>>t;
while(t--)
{
int starts,ends,n;
cin>>starts>>ends;
V=ends-starts;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>W[i]>>C[i];
}
memset(dp,INF ,sizeof(dp));
dp[0]=0;
for(int i=1;i<=n;i++)
for(int j=C[i];j<=V;j++)
dp[j]=min(dp[j],dp[j-C[i]]+W[i]);
if(dp[V]!=INF)
printf("The minimum amount of money in the piggy-bank is %d.\n",dp[V]);
else
printf("This is impossible.\n");
}
return 0;
}