-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKNAP.C
More file actions
111 lines (80 loc) · 2.04 KB
/
Copy pathKNAP.C
File metadata and controls
111 lines (80 loc) · 2.04 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include<stdio.h>
#include<conio.h>
void knapsack(int n, float weight[], float profit[], float capacity)
{
float x[20],tp;
int i,j,rcap;
tp = 0;
rcap = capacity;
for (i = 0; i < n; i++)
x[i] = 0.0;
for (i = 0; i < n; i++)
{
if (weight[i] > rcap)
break;
else
{
x[i] = 1.0;
tp = tp + profit[i];
rcap = rcap - weight[i];
}
}
if (i < n)
x[i] = rcap / weight[i];
tp = tp + (x[i] * profit[i]);
printf("\nThe result vector is = {");
for (i=0; i<n-1; i++)
printf("%0.2f, ",x[i]);
printf("%0.2f}\n",x[i]);
printf("\nMaximum profit is = %0.3f",tp);
}
void main()
{
float weight[20], profit[20], ratio[20], capacity;
int num,i,j;
float temp;
clrscr();
printf("Enter the no. of items : ");
scanf("%d",&num);
printf("\nEnter the capacity of knapsack : ");
scanf("%f",&capacity);
printf("\nEnter the wights and profits of each object.....\n");
for (i = 0; i < num; i++)
{
printf("Item no. %d : ",i+1);
scanf("%f%f",&weight[i],&profit[i]);
}
for (i = 0; i < num; i++)
ratio[i] = profit[i] / weight[i];
for (i = 1; i < num; i++)
for (j = 0; j < num-i; j++)
if (ratio[j] < ratio[j+1])
{
temp = ratio[j];
ratio[j] = ratio[j+1];
ratio[j+1] = temp;
temp = weight[j];
weight[j] = weight[j+1];
weight[j+1] = temp;
temp = profit[j];
profit[j] = profit[j+1];
profit[j+1] = temp;
}
knapsack(num, weight, profit, capacity);
getch();
}
/*
OUTPUT :
Enter the no. of items : 7
Enter the capacity of knapsack : 15
Enter the wights and profits of each object.....
Item no. 1 : 2 10
Item no. 2 : 3 5
Item no. 3 : 5 15
Item no. 4 : 7 7
Item no. 5 : 1 6
Item no. 6 : 4 18
Item no. 7 : 1 3
The result vector is = {1.00, 1.00, 1.00, 1.00, 1.00, 0.67, 0.00}
Maximum profit is = 55.333
*/