Techknow Study

KNAPSACK:

8:47:00 PM vikas 0 Comments Category :

KNAPSACK:

IT is a problem in which we have items with
their weight  & values respective & provided
a knapsack with a given capacity.

OUR objective is to find that subnet of items
which can fit in the Knapsack .So as to maximize

total project to design a recursive equation
for 0/1 KNAPSACK.

pictured EXAMPLE:-


PROGRAM:_

#include<stdio.h>
#include<conio.h>
int max(int a,int b)
{
    if(a>b)
    return a;
    else
    return b;
}



void main()
{
    int w[10],p[10],i,m,n;
    int v[10][10],j;
    clrscr();
    printf("ENTER THE NUMBER OF ITEMS:");
    scanf("%d",&n);
    printf("ENTER THE WEIGHT OF THE ITEMS:");
    for(i=1;i<=n;i++)
    scanf("%d",&w[i]);
    printf("ENTER THE VALUES OF THE ITEMS:");
    for(i=1;i<=n;i++)
    scanf("%d",&p[i]);
    printf("ENTER THE CAPACITY OF KNAPSACK:");
    scanf("%d",&m);
    for(i=0;i<=n;i++)
    {
    for(j=0;j<=m;j++)
    {
        if(i==0||j==0)
        {
        v[i][j]=0;
        }
        else if(j<w[i])
        {
        v[i][j]=v[i-1][j];
        }

       else
        {
        v[i][j]=max(v[i-1][j],v[i-1][j-w[i]]+p[i]);
        }
    }
    }
    for(i=0;i<=n;i++)
    {
    for(j=0;j<=m;j++)
    {
        printf("%d\t",v[i][j]);
        }
    printf("\n");
    }
    printf("\nthe optimal solution is\t%d\t",v[n][m]);

    getch();
}

RELATED POSTS

0 comments