-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathfractional_knapsack.c
49 lines (42 loc) · 1.04 KB
/
fractional_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
//fractional knapsack using greedy algorithum
#include<stdio.h>
struct data{
int price;
int weight;
float r;
};
int main(){
int cap;
printf("Enter the capacity :");
scanf("%d", &cap);
int n, i, j;
printf("Enter the number of objects :");
scanf("%d", &n);
struct data a[n];
printf("Enter the price and weight of an object respectively\n");
for(i=0; i<n; i++){
scanf("%d %d", &a[i].price, &a[i].weight);
a[i].r = (float) a[i].price/a[i].weight;
}
for(i=0; i<n; i++){
for(j=0; j<n-i-1; j++){
if(a[j].r < a[j+1].r){
struct data temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
float ans = 0;
for(i=0; i<n && cap>0; i++){
if ( cap >= a[i].weight ){
ans += a[i].price;
cap -= a[i].weight;
}
else if(cap > 0){
ans += (float) cap/a[i].weight*a[i].price;
cap =0;
}
}
printf("The answer is %.2f", ans);
}