knapsack C language

/* A naive recursive implementation
* of 0-1 Knapsack problem
*/
#include <stdio.h>
// A utility function that returns
// maximum of two intergers
int max(int left, int right){
    return left > right ? left: right;
}
/*
* Returns the maximum value that can be
* put in a knapsack of capacity W
*/
int knapsack(int W, int wt[], int vl[], int n){
    //Base case
    if(W == 0 || n == 0)
        return 0;
    /*
    * If weight of the nth item is more than
    * knapsack capacity W, then this item cannot
    * be included in the optimal solution.
    */
    if(wt[n - 1] > W)
        return knapsack(W, wt, vl, n - 1);
    /**
    * Return the maximum of two cases:
    * (1) nth item included 
    * (2) not included
    */
    else
        return max(vl[n - 1] + knapsack(W - wt[n - 1], wt, vl, n-1),
            knapsack(W, wt, vl, n - 1)
        );
}

//Driver program to test above function
int main(){
    
    int wt[] = {10, 20, 30};
    int vl[] = {60, 100, 120}; 
    int n = sizeof(wt) / sizeof(wt[0]);
    printf("The maximum sum of values:%5d\n", knapsack(50, wt, vl,n));
    
    return 0;
}

猜你喜欢

转载自blog.csdn.net/s15948703868/article/details/108003263
今日推荐