Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/159.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 0-1整数背包返回错误答案(动态规划)_C++_Vector_Dynamic Programming_Knapsack Problem - Fatal编程技术网

C++ 0-1整数背包返回错误答案(动态规划)

C++ 0-1整数背包返回错误答案(动态规划),c++,vector,dynamic-programming,knapsack-problem,C++,Vector,Dynamic Programming,Knapsack Problem,这个标题很容易解释,我已经摆弄了好几天了。我做错了什么蠢事?问题是对于一堆重量相同的材料,因此没有值的输入向量,因此可能是因为我没有在std::max部分中添加值,但我尝试过这样做,也没有得到正确的答案。W是背包的容量,W是由物品重量组成的向量 #include <iostream> #include <vector> using std::vector; using std::max; int optimal_weight(int W, const vector&l

这个标题很容易解释,我已经摆弄了好几天了。我做错了什么蠢事?问题是对于一堆重量相同的材料,因此没有值的输入向量,因此可能是因为我没有在std::max部分中添加值,但我尝试过这样做,也没有得到正确的答案。W是背包的容量,W是由物品重量组成的向量

#include <iostream>
#include <vector>

using std::vector;
using std::max;

int optimal_weight(int W, const vector<int> &w) {
     size_t size = w.size();
     int knapsack[size+1][W+1];

     for (size_t a = 0; a <= size; a++) {
         knapsack[a][0] = 0;
     }

     for (int b = 0; b <= W; b++) {
         knapsack[0][b] = 0;
     }

     for (size_t i = 1; i <= size; i++) {
          for (int j = 0; j <= W; j++) {
                   knapsack[i][j] = knapsack[i-1][j];

                   if (w[i-1] <= j) {
                          knapsack[i][j] = std::max(knapsack[i-1][j-w[i-1]], knapsack[i-1][j]);
                    }

                }
         }
      return knapsack[size][W];
    }
#包括
#包括
使用std::vector;
使用std::max;
整数最优权(整数W,常数向量&W){
尺寸=w.尺寸();
智力背包[尺寸+1][W+1];

对于(size_t a=0;a代码中的行:
int-knapsack[size][W+1]

应更改为:
int背包[size+1][W+1]

这是因为数组是从
0
索引的,在上述情况下,数组是为
0定义为size-1
的,您访问的元素是
index=size

在计算
std::max

时,也要添加相应的权重。您能给出一个示例输入、预期和实际输出吗?另外,您能提供一个吗?背包数组错误是一个输入错误,当它是[size+1]时仍然不起作用。但是,在std::max期间添加相应的权重是什么意思?我已经解释过,在这个程序中没有“值”。我是否应该添加其他内容来代替它?