
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
0-1 Knapsack Problem in C?
A knapsack is a bag. And the knapsack problem deals with the putting items to the bag based on the value of the items. It aim is to maximise the value inside the bag. In 0-1 Knapsack you can either put the item or discard it, there is no concept of putting some part of item in the knapsack.
Sample Problem
Value of items = {20, 25,40} Weights of items = {25, 20, 30} Capacity of the bag = 50
Weight distribution
25,20{1,2} 20,30 {2,3} If we use {1,3} the weight will be above the max allowed value. For {1,2} : weight= 20+25=45 Value = 20+25 = 45 For {2,3}: weight=20+30=50 Value = 25+40=65
The maximum value is 65 so we will put the item 2 and 3 in the knapsack.
PROGRAM FOR 0-1 KNAPSACK PROBLEM
#include<stdio.h> int max(int a, int b) { if(a>b){ return a; } else { return b; } } int knapsack(int W, int wt[], int val[], int n) { int i, w; int knap[n+1][W+1]; for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i==0 || w==0) knap[i][w] = 0; else if (wt[i-1] <= w) knap[i][w] = max(val[i-1] + knap[i-1][w-wt[i-1]], knap[i-1][w]); else knap[i][w] = knap[i-1][w]; } } return knap[n][W]; } int main() { int val[] = {20, 25, 40}; int wt[] = {25, 20, 30}; int W = 50; int n = sizeof(val)/sizeof(val[0]); printf("The solution is : %d", knapsack(W, wt, val, n)); return 0; }
Output
The solution is : 65
- Related Articles
- C++ Program to Solve the 0-1 Knapsack Problem
- Python Program for 0-1 Knapsack Problem
- Printing Items in 0/1 Knapsack in C++
- Fractional Knapsack Problem
- 0/1 Knapsack using Branch and Bound in C++
- 0/1 Knapsack using Branch and Bound in C/C++?
- C++ Program to Solve the Fractional Knapsack Problem
- C++ Program to Solve Knapsack Problem Using Dynamic Programming
- Program to implement the fractional knapsack problem in Python
- Activity Selection Problem (Greedy Algo-1) in C++?
- Program to find maximum value we can get in knapsack problem by taking multiple copies in Python
- Problem with division as output is either 0 or 1 when using ifthenelse condition in ABAP program
- Partition Problem in C++
- Difference between while(1) and while(0) in C/C++
- Fitting Shelves Problem in C++

Advertisements