Knapsack problem

#include<stdio.h>
void kanpsack(int ,int[],int[],int);
int max(int,int);
int main()
{
 int capacity,n;
 printf("enter the number of items:");
 scanf("%d",&n);
 int weights[n],profits[n];
 printf("enter weights the of items:");
 for(int i=0;i<n;i++)
 {
  scanf("%d",&weights[i]);
 }
 printf("enter profits the of items:");
 for(int i=0;i<n;i++)
 {
  scanf("%d",&profits[i]);
 }
 printf("enter the capacity of knapsack:");
 scanf("%d",&capacity);
 kanpsack(n,weights,profits,capacity);
 return 0;
}
void kanpsack(int n,int weights[],int profits[],int capacity)
{
 int dp[n+1][capacity+1];
 for(int i=0;i<=n;i++)
 {
  for(int w=0;w<=capacity;w++)
  {
   if(i==0||w==0)
   {
    dp[i][w]=0;
   }
   else if(weights[i-1]<=w)
   {
    dp[i][w] = max(profits[i - 1] + dp[i - 1][w - weights[i - 1]], dp[i - 1][w]);
   }
   else
   {
    dp[i][w]=dp[i-1][w];
   }
  }
 }
 printf("max profit is :%d",dp[n][capacity]);
 int w=capacity;
 printf("\nitems included in the knapsack:");
 for(int i=n;i>0&&w>0;i--)
 {
  if(dp[i][w]!=dp[i-1][w])
  {
   printf("%d ",i);
   w-=weights[i-1];
  }
 }
 printf("\n");
}
int max(int a,int b)
{
 return(a>b)?a:b;
}

Comments

Popular posts from this blog

AVL Trees

BFS Matrix

BFS List