C 打印背包物品(允许重复物品)

C 打印背包物品(允许重复物品),c,algorithm,knapsack-problem,C,Algorithm,Knapsack Problem,我实现了两种解决背包问题的方法,但我不能用一种方法打印选定的项目,而另一种方法效果不好,因为它忽略了我的第一个项目值。实际上,我的背包问题是将一根长度为N的棒划分为长度为1,2,…,N的子棒,其中每个子棒有不同的成本 当然,只要不超过长度,就允许重复项目。 因此: 1) 我有一个长度为N的条,可以分开。从1到N的每个分区都有一个与价格相关的分区。 2) 背包寻找最大的利润,在那里可以采取多次相同的项目。 3) 打印背包选择的元素 我的问题是: 1) 在第一段代码中,我无法理解如何打印所选项目。

我实现了两种解决背包问题的方法,但我不能用一种方法打印选定的项目,而另一种方法效果不好,因为它忽略了我的第一个项目值。实际上,我的背包问题是将一根长度为N的棒划分为长度为1,2,…,N的子棒,其中每个子棒有不同的成本

当然,只要不超过长度,就允许重复项目。 因此: 1) 我有一个长度为N的条,可以分开。从1到N的每个分区都有一个与价格相关的分区。 2) 背包寻找最大的利润,在那里可以采取多次相同的项目。 3) 打印背包选择的元素

我的问题是: 1) 在第一段代码中,我无法理解如何打印所选项目。 2) 我尝试了矩阵方法,但我不明白如何设置背包矩阵的方程,允许重复项目

这是我第一次尝试,这确实有效,并给了我正确的答案,但我真的无法理解如何打印所选项目

int *k = malloc(sizeof(int ) * lenght+1);
for( i = 0 ; i <= lenght; i++) k[i] = 0;
int*k=malloc(sizeof(int)*长度+1);

对于(i=0;i仅当元素“保存在背包中”时,才应打印该元素。每次迭代时,您都要检查是将元素放入背包还是丢弃它。在代码中,您应该检查以下内容:如果元素“保存在背包中”,则打印它及其重量,以及其他值​​背包中已经存在的元素,并且添加此元素时不会超过背包的容量。有几种方法可以做到这一点。我考虑过这一点:在执行该方法时,保存选定的值​​在背包中,每个可能的容量(如果容量为W,则必须存储选定的值​​在矩阵中,其中每行w表示一个值0
for(i = 0 ; i <= lenght ; i++){
    for(w = 0 ; w < lenght ; w++){
        if( bar[w] <= i){
            k[i] = searchmax( prices[w] + k[i-bar[w]] , k[i] );
        } 
    }
}
int **k = malloc(sizeof(int*) * (lenght+1));
for(i=0;i<=lenght;i++) k[i] = malloc(sizeof(int)*(lenght+1));

for( i = 0 ; i <= lenght; i++)k[0][i]= 0;
for(i = 0 ; i <=lenght;i++) k[i][0]=0;

for(i=1;i<=lenght;i++){
    for(w=1;w<=lenght;w++){
        if(bar[i]<=w){
            printf("\nPrices: %d  Barlenght: %d" , prices[i], bar[i]);
            k[i][w]=searchmax(prices[i]+k[i][w-bar[i]], k[i-1][w]);
        }
        else k[i][w] = k[i-1][w];

    }
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>
#include <string>


/**
* Responsible for dealing with the unbounded knapsack problem.
*/
class UnboundedKnapsack
{
    //-------------------------------------------------------------------------
    //      Attributes
    //-------------------------------------------------------------------------
    /**
    * Stores maximum value of the knapsack for a certain capacity.
    */
    std::vector<int> knapsack;

    /**
    * Stores elements that are part of the knapsack with a certain capacity.
    * <li><b>Line:</b> Knapsack capacity</li>
    * <li><b>Column:</b> Elements</li>
    */
    std::vector<std::vector<int> > selectedElements;

    /**
    * Stores maximum knapsack capacity.
    */
    int maximumCapacity;


public:
    //-------------------------------------------------------------------------
    //      Constructor
    //-------------------------------------------------------------------------
    UnboundedKnapsack()
    {
        maximumCapacity = -1;
    }


    //-------------------------------------------------------------------------
    //      Destructor
    //-------------------------------------------------------------------------
    ~UnboundedKnapsack()
    {
        delete this;
    }


    //-------------------------------------------------------------------------
    //      Methods
    //-------------------------------------------------------------------------
    /**
    * Unbounded knapsack allows to use one or more occurrences of an item.
    *
    * @param        w Weight of the elements
    * @param        v Value of the elements
    * @param        N Number of itens
    * @param        W Maximum weight capacity
    * @return       This object to allow chained calls
    */
    UnboundedKnapsack* knapsack_unbounded(std::vector<int>& w, std::vector<int>& v, int N, int W)
    {
        // Stores the maximum value which can be reached with a certain capacity
        knapsack.clear();
        knapsack.resize(W + 1);

        maximumCapacity = W + 1;

        // Stores selected elements with a certain capacity
        selectedElements.resize(W + 1);

        // Initializes maximum value vector with zero
        for (int i = 0; i < W + 1; i++) {
            knapsack[i] = 0;
        }

        // Computes the maximum value that can be reached for each capacity
        for (int capacity = 0; capacity < W + 1; capacity++) {
            // Goes through all the elements
            for (int n = 0; n < N; n++) {
                if (w[n] <= capacity) {
                    // max(knapsack[capacity], knapsack[capacity - w[n]] + v[n])
                    if (knapsack[capacity] <= knapsack[capacity - w[n]] + v[n]) {
                        knapsack[capacity] = knapsack[capacity - w[n]] + v[n];

                        // Stores selected elements
                        selectedElements[capacity].clear();
                        selectedElements[capacity].push_back(n + 1);

                        for (int elem : selectedElements[capacity - w[n]]) {
                            selectedElements[capacity].push_back(elem);
                        }
                    }
                }
            }
        }

        return this;
    }

    /**
    * Returns maximum value for a certain number of elements and a certain
    * capacity.
    *
    * @param        capacity Capacity of the knapsack
    * @return       Maximum possible value with capacity provided
    * @throws       std::invalid_argument If capacity provided is out of bounds
    */
    int getMaximumValue(int capacity)
    {
        if (capacity < 0 || capacity >= maximumCapacity)
            throw std::invalid_argument("Capacity out of bounds");

        return knapsack[capacity];
    }

    /**
    * Returns elements that belong to the knapsack with a certain capacity.
    *
    * @param        capacity Capacity of the knapsack
    * @return       Elements that are part of the knapsack with the capacity
    * provided
    * @throws       std::invalid_argument If capacity provided is out of bounds
    * @apiNote      Elements are referenced by their index + 1
    */
    std::vector<int>& getSelectedElements(int capacity)
    {
        if (capacity < 0 || capacity >= maximumCapacity)
            throw std::invalid_argument("Capacity out of bounds");

        return selectedElements[capacity];
    }

    /**
    * Returns elements that are part of the knapsack with a certain capacity.
    * This method will return a {@link std::string} with the following format:
    * <code>[elem1, elem2, elem3...]</code>
    *
    * @param        capacity Capacity of the knapsack
    * @return       Elements that are part of the knapsack with the capacity
    * provided
    * @apiNote      Elements are referenced by their index + 1
    */
    std::string selectedElements_toString(int capacity)
    {
        std::string response = "[";

        for (int element : selectedElements[capacity]) {
            response.append(std::to_string(element));
            response.append(", ");
        }

        // Removes last ", "
        response.pop_back();
        response.pop_back();

        response.append("]");

        return response;
    }
};


//-------------------------------------------------------------------------
//      Main
//-------------------------------------------------------------------------
/**
* Example made based on this exercise:
* {@link https://www.urionlinejudge.com.br/repository/UOJ_1487_en.html}
*/
int main()
{
    UnboundedKnapsack* knapsack = new UnboundedKnapsack();
    int totalCapacity = 60, elements = 5;
    std::vector<int> elements_weight = { 10, 20, 5, 50, 22 };
    std::vector<int> elements_values = { 30, 32, 4, 90, 45 };

    knapsack->knapsack_unbounded(elements_weight, elements_values, elements, totalCapacity);

    std::cout << "Maximum value: "
        << knapsack->getMaximumValue(totalCapacity)
        << std::endl;
    std::cout << "Selected elements: "
        << knapsack->selectedElements_toString(totalCapacity)
        << std::endl;

    system("pause");

    return 0;
}
Maximum value: 180
Selected elements: [1, 1, 1, 1, 1, 1]