From e7d4f50b766be809373a465767dfe3e05ac2ad37 Mon Sep 17 00:00:00 2001 From: Haidong Ji Date: Wed, 26 Dec 2018 20:27:48 -0600 Subject: Knapsack maximize gold done! Interesting signal 11 segmentation fault problem. Once I changed the 2D array to 2D vector, it worked: // int value[W + 1][j + 1]; vector< vector > value(W + 1, vector(j + 1));--- PlaygroundCpp/Sources/Playground.cpp | 79 +++++++++++++----------------------- 1 file changed, 29 insertions(+), 50 deletions(-) diff --git a/PlaygroundCpp/Sources/Playground.cpp b/PlaygroundCpp/Sources/Playground.cpp index e402792..50297b2 100644 --- a/PlaygroundCpp/Sources/Playground.cpp +++ b/PlaygroundCpp/Sources/Playground.cpp @@ -1,67 +1,46 @@ #include -#include #include //#include using std::vector; -int lcs3(vector &a, vector &b, vector &c) { - int l = c.size(); - int m = b.size(); - int n = a.size(); - int D[n + 1][m + 1][l + 1]; - for (int k = 0; k < l + 1; k++) { - for (int j = 0; j < m + 1; j++) { - for (int i = 0; i < n + 1; i++) { - if (i == 0 || j == 0 || k == 0) { - D[i][j][k] = 0; - continue; - } - if (a[i - 1] == b[j - 1] && b[j - 1] == c[k - 1]) { - D[i][j][k] = D[i - 1][j - 1][k - 1] + 1; - } else { - D[i][j][k] = std::max(D[i - 1][j][k], - std::max(D[i][j - 1][k], D[i][j][k - 1])); +int optimalWeight(int W, vector &w2) { + int j = w2.size(); +// int value[W + 1][j + 1]; + vector< vector > value(W + 1, vector(j + 1)); + + for (int i = 0; i < j + 1; i++) { + for (int w = 0; w < W + 1; w++) { + if (i == 0 || w == 0) { + value[w][i] = 0; + continue; + } + value[w][i] = value[w][i - 1]; + if (w2[i - 1] <= w) { + int val = value[w - w2[i - 1]][i - 1] + w2[i - 1]; + if (value[w][i] < val) { + value[w][i] = val; } } } + } - return D[n][m][l]; + return value[W][j]; } -//TEST(LCS3, t1) { -// vector a = { 1, 2, 3 }; -// vector b = { 2, 1, 3 }; -// vector c = { 1, 3, 5 }; -// ASSERT_EQ(2, lcs3(a, b, c)); -//} -// -//TEST(LCS3, t2) { -// vector a = { 8, 3, 2, 1, 7 }; -// vector b = { 8, 2, 1, 3, 8, 10, 7 }; -// vector c = { 6, 8, 3, 1, 4, 7 }; -// ASSERT_EQ(3, lcs3(a, b, c)); +//TEST(Knapsack, t1) { +// vector w = { 1, 4, 8 }; +// int W = 10; +// ASSERT_EQ(9, optimalWeight(W, w)); //} int main() { - size_t an; - std::cin >> an; - vector a(an); - for (size_t i = 0; i < an; i++) { - std::cin >> a[i]; - } - size_t bn; - std::cin >> bn; - vector b(bn); - for (size_t i = 0; i < bn; i++) { - std::cin >> b[i]; - } - size_t cn; - std::cin >> cn; - vector c(cn); - for (size_t i = 0; i < cn; i++) { - std::cin >> c[i]; - } - std::cout << lcs3(a, b, c) << std::endl; + int n, W; + std::cin >> W >> n; + vector w(n); + for (int i = 0; i < n; i++) { + std::cin >> w[i]; + } + std::cout << optimalWeight(W, w) << '\n'; } -- cgit v1.2.3