-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6.GREEDYKNAPSACK.CPP
More file actions
97 lines (83 loc) · 1.17 KB
/
6.GREEDYKNAPSACK.CPP
File metadata and controls
97 lines (83 loc) · 1.17 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
#include<stdio.h>
#include<conio.h>
void knapsak(float s[],float w[],float p[],int n)
{
int i,j;
float t,temp;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if (s[j]<s[j+1])
{
temp=s[j];
s[j]=s[j+1];
s[j+1]=temp;
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
temp=w[j];
w[j]=w[j+1];
w[j+1]=temp;
}
}
}
}
int main()
{
//clrscr();
//textcolor(11);
int m,n ,i,rest ;
float p[10],w[10],s[10],x[10],profit;
printf("Bag size: ");
scanf("%d",&m);
printf("How many item: ");
scanf("%d",&n);
//textcolor(4);
for (i=0;i<n;i++)
{
printf("\n%d. ",i);
printf("weight: ");
scanf("%f",&w[i]);
printf(" profit: ");
scanf("%f",&p[i]);
}
for(i=0;i<n;i++)
{
s[i]=p[i]/w[i];
}
knapsak(s,w,p,n);
rest=m;
profit=0;
for(i=0;i<n;i++)
{
x[i]=0.0;
}
for(i=0;i<n;i++)
{
if(w[i]>rest)
break;
x[i]=1.0;
profit=profit+p[i];
rest=rest-w[i];
}
if(i<n)
{
x[i]=rest/w[i];
profit=profit+(x[i]*p[i]);
}
for (i=0;i<n;i++)
{
printf("\t%.2f",w[i]);
printf("\t%.2f",p[i]);
printf("\n");
}
printf("\n");
for(i=0;i<n;i++)
{
printf("\t%.2f",x[i]);
}
//textcolor(2);
printf("\n\nprofit: %.2f",profit);
return 0;
}