在N件物品取出若干件放在容量为W的背包里,每件物品的体积为W1,W2……Wn(Wi为整数),与之相对应的价值为P1,P2……Pn(Pi为整数)。求背包能够容纳的最大价值。
Input
第1行,2个整数,N和W中间用空格隔开。N为物品的数量,W为背包的容量。(1 <= N <= 100,1 <= W <= 10000) 第2 - N + 1行,每行2个整数,Wi和Pi,分别是物品的体积和物品的价值。(1 <= Wi, Pi <= 10000)
Output
输出可以容纳的最大价值。
Input示例
3 6 2 5 3 8 4 9
Output示例
14
李陶冶 (题目提供者)
C++的运行时限为:1000 ms ,空间限制为:131072 KB 示例及语言说明请按这里
#include<bits/stdc++.h>
using namespace std;
const int x=110,y=11000;
int w[x],p[x];
int dp[y];
int main()
{
int N,W;
cin>>N>>W;
for(int i=1;i<=N;i++) cin>>w[i]>>p[i];
for(int i=1;i<=N;i++)
for(int j=W;j>=w[i];j--)
{
dp[j]=max(dp[j-w[i]]+p[i],dp[j]);
}
cout<<dp[W]<<endl;
return 0;
}