Backpack Problem 01

There are N items and a knapsack with capacity V. Each item can only be used once.

The i-th item has volume vi and value wi.

Solving which items to put into the backpack can make the total volume of these items not exceed the capacity of the backpack, and the total value is the largest.
output the maximum value.

input format

In the first line, two integers, N and V, are separated by spaces, representing the number of items and the volume of the backpack respectively.

Next there are N lines, each line has two integers vi, wi, separated by spaces, representing the volume and value of the i-th item respectively.

output format

Output an integer representing the maximum value.

data range

0<N,V≤1000
0<vi,wi≤1000

input sample

4 5
1 2
2 4
3 4
4 5

Sample output:

8

#include<bits/stdc++.h>
using namespace std;
const int N=1010;
int f[N];
int V[N],W[N];
int main()
{
    int n,m;
    cin>>n>>m;
    for(int i=1;i<=n;i++) cin>>V[i]>>W[i];
    for(int i=1;i<=n;i++) 
        for(int j=m;j>=V[i];j--) 
           f[j]=max(f[j],f[j-V[i]]+W[i]);
    cout<<f[m]<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/2302_77099705/article/details/130985849