Skip to content

Instantly share code, notes, and snippets.

@murasesyuka
Last active March 15, 2017 11:57
Show Gist options
  • Select an option

  • Save murasesyuka/eeb5a88b36218585fd32b3e54ccab515 to your computer and use it in GitHub Desktop.

Select an option

Save murasesyuka/eeb5a88b36218585fd32b3e54ccab515 to your computer and use it in GitHub Desktop.
read chokudai book with C++
#include <bits/stdc++.h>
using namespace std;
//
// P. 177 knapsack
// g++ -O3 knapsack2.cpp -std=gnu++1y && ./a.out
//
int knapsack2(int n, int w){
int ws[5] = {3,4,1,2,3};
int ps[5] = {2,3,2,3,6};
int maxw = 10;
if (w > maxw) return -1;
if (n >= 5) return 0;
return max( knapsack2(n+1, w),
knapsack2(n+1, w+ws[n]) + ps[n]);
}
int knapsack_dp(){
int ws[5] = {3,4,1,2,3};
int ps[5] = {2,3,2,3,6};
int dp[6][11] = {0};
int maxw = 10;
int ret = 0;
for(int i = 0; i < 5; ++i)
{
for(int j = 0; j < maxw; ++j)
{
if(j+ws[i] <= maxw)
{
//cout << i << ':' << j << " :: " << dp[i+1][j+ws[i]] << '/' << dp[i][j] + ps[i] << endl;
dp[i+1][j+ws[i]] = max( dp[i+1][ j+ws[i] ], dp[i][j] + ps[i]);
ret = max(dp[i+1][j+ws[i]], ret);
}
}
}
return ret;
}
int knapsack_dp_cpp14(){
array<int,5> ws{3,4,1,2,3};
array<int,5> ps{2,3,2,3,6};
array<array<int, 6>, 11> dp{};
const int maxw = 10;
int ret = 0;
for(int i = 0; i < 5; ++i){
for(int j = 0; j <= maxw; ++j){
if(j+ws[i] <= maxw)
{
//cout << i << ':' << j << " :: " << dp[i+1][j+ws[i]] << '/' << dp[i][j] + ps[i] << endl;
//dp[i+1][j+ws[i]] = max(dp[i+1][j+ws[i]], dp[i][j] + ps.at(i));
dp[i+1][j+ws[i]] = max(dp[i+1][j+ws[i]], dp[i][j] + ps[i]);
ret = max(dp[i+1][j+ws[i]], ret);
}
}
}
return ret;
}
int main(){
cout << "knapsack" << endl;
cout << knapsack2(0, 0) << endl; //=> 15
cout << knapsack_dp() << endl; //=> 14
cout << knapsack_dp_cpp14() << endl; //=> 14
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment