-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKnapSack.c
71 lines (70 loc) · 1.43 KB
/
KnapSack.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include<stdio.h>
#include<stdlib.h>
#define MAX 500
int n,c,weight[MAX],profit[MAX],vector [MAX][MAX],x[MAX];
int max(int,int);
void knapsack();
void printsoln();
int main()
{
printf("Enter the number of weights:");
scanf("%d",&n);
printf("Enter the capacity of knapsack:");
scanf("%d",&c);
int i,j;
printf("Enter the value of weights:");
for(i=1;i<=n;i++)
scanf("%d",&weight[i]);
printf("Enter the value profits:");
for(i=1;i<=n;i++)
scanf("%d",&profit[i]);
knapsack();
printsoln();
for(i=0;i<=n;i++)
{
for(j=0;j<=c;j++)
{
printf("%2d ",vector[i][j]);
}
printf("\n");
}
printf("Maximum profit is %d \n",vector[n][c]);
printf("Objects considered are\n");
for(i=1;i<=n;i++)
if(x[i]==1)
printf("object no=%d weight=%d profit=%d\n",i,weight[i],profit[i]);
return 0;
}
int max(int a,int b)
{
return a>b?a:b;
}
void knapsack()
{
int i,j;
for(i=0;i<=n;i++)
{
for(j=0;j<=c;j++)
{
if(i==0 || j==0)
vector[i][j]=0;
else if(j-weight[i]<0)
vector[i][j]=vector[i-1][j];
else
vector[i][j]=max(vector[i-1][j],vector[i-1][j-weight[i]]+profit[i]);
}
}
}
void printsoln()
{
int i=n,j=c;
while(i!=0||j!=0)
{
if(vector[i][j]!=vector[i-1][j])
{
x[i]=1;
j=j-weight[i];
}
i--;
}
}