Programming Algorithm-Knapsack Problem (recursion) code (c)

Source: Internet
Author: User
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








Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.