Description] [Title
a traveler can hold a maximum of M kg backpack, there are n items, their weight are W1, W2, ..., Wn, their value are C1, C2, ... , Cn, travelers can seek to maximize the total value.
[Input]
The first line: two integers, M (backpack capacity, M≤200) and N (number of items, N≤30);
First 2..N + 1 line: two integers each line Wi, Ci, and represents the weight value of each item.
[Output]
is only one line, a number that indicates the maximum total value.
[Input] Sample
10. 4
2. 1
. 3. 3
. 4. 5
. 7. 9
[Output] Sample
12
Dynamic programming method
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define N 1001
using namespace std;
int m,n;
int w[N],c[N],f[N];
void fun(int cost,int weight)
{
for(int v=m;v>=weight;v--)
f[v]=max(f[v],f[v-weight]+cost);
}
int main(){
cin>>m>>n;
for(int i=1; i<=n; ++i)
cin>>w[i]>>c[i];
for(int i=1; i<=n; ++i){
fun(c[i],w[i]);
}
cout<<f[m]<<endl;
return 0;
}