Knapsack problem: full knapsack problem

  • Complete knapsack problem
    and 01 backpack is similar, but where each item can be selected multiple times

Problem Description

有 N 种物品和一个容量是 V 的背包,每种物品都有无限件可用。

第 i 种物品的体积是 vi,价值是 wi。

求解将哪些物品装入背包,可使这些物品的总体积不超过背包容量,且总价值最大。
输出最大价值。

Input format
of the first row two integers, N, V, separated by spaces, the number and types of items each represent a backpack volume.

Then there are N rows, each row two integers vi, wi, separated by spaces, respectively, and the volume of the i-th value of the article.

Output format
output an integer representing the maximum value.

Sample

输入样例
4 5
1 2
2 4
3 4
4 5
输出样例:
10

Because each item can be selected multiple times, so the current status can be updated by the current status = over, and so the difference between the 01 backpack is small to large enumeration

Code

#include<iostream>
#include<algorithm>
using namespace std;
int f[1010];
int n;
int m;
int main(){
    cin >> n >> m;
    while(n--){
        int a, b;
        cin >> a >> b;
        for(int i = a; i <= m; i++)
            f[i] = max(f[i - a] + b, f[i]);
    }
    cout << f[m] << endl;
    return 0;
}
Published 68 original articles · won praise 166 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_45432665/article/details/104186278