Knapsack Problem (recursion) code (c)
Address: http://blog.csdn.net/caroline_wendy
Question: There are n items whose weight and value are respectively W and V. From these items, select the items whose total weight does not exceed W and find the maximum value of the total value in all the selection schemes.
That is, the classic dynamic planning problem.
AvailableDeep Priority Search, Traverse each part to select the optimal solution,Not the bestMethod.
Code:
/* * main.cpp * * Created on: 2014.7.17 * Author: spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <limits.h>#include <utility>#include <queue>#include <algorithm>using namespace std;class Program {static const int MAX_N = 10000;int n=4, W=5;int w[MAX_N] = {2,1,3,2}, v[MAX_N]={3,2,4,2};int rec (int i, int j) {int res;if (i==n) {res = 0;} else if (j<w[i]) {res = rec(i+1, j);} else {res = max(rec(i+1,j), rec(i+1, j-w[i])+v[i] );}return res;}public:void solve() {printf("result = %d\n", rec(0, W));}};int main(void){Program P;P.solve(); return 0;}
Output:
result = 7