Description
Cyin拿到TX的第一份工资,马上实施他的购书计划了。算法已经不能满足cyin了,他打算称霸数据挖掘领域。但TX太抠了,Cyin的购书计划不能一步到位。于是,Cyin打算用尽可能多的钱来买书。请聪明的你,算算Cyin最多能花多少钱?
Input
第一行S,表示Cyin的工资(0 < S < 2000)
第二行n, 表示书的种类(0< n < 2000)
第三行有n个整数,表示每本书的价格pi ( pi <= S)
多组数据输入,且所有数据均为整数。
Output
输出cyin最多能花多少钱,并换行。
Sample Input
5
2
3 4
10
5
2 3 4 4 5
Sample Output
4
10
Hint
注意多组数据
解题思路:
这是一个典型的01背包问题。
#include<iostream>
using namespace std;
const int maxN = 3000;
int pi[maxN];
int B[maxN];
int main()
{
int s;
while(cin>>s)
{
int n;
cin>>n;
for(int i=0;i<n;++i)
cin>>pi[i];
for(int i=0;i<=s;++i)
B[i] = 0;
for(int i=0;i<n;++i)
{
int w = s;
while(w>=pi[i])
{
if(B[w-pi[i]]+pi[i]>B[w])
B[w] = B[w-pi[i]]+pi[i];
--w;
}
}
cout<<B[s]<<endl;
}
return 0;
}
最后欢迎大家访问我的个人网站: 1024s