-
Notifications
You must be signed in to change notification settings - Fork 0
/
Fractional knapsack
88 lines (71 loc) · 2.12 KB
/
Fractional knapsack
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
//Fractional knapsack
import java.io.*;
import java.lang.*;
import java.util.*;
class Item {
int value, weight;
Item(int x, int y) {
this.value = x;
this.weight = y;
}
}
class GfG {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while(t-- > 0) {
String inputLine[] = br.readLine().trim().split(" ");
int n = Integer.parseInt(inputLine[0]);
int w = Integer.parseInt(inputLine[1]);
Item[] arr = new Item[n];
inputLine = br.readLine().trim().split(" ");
for(int i = 0, k = 0; i < n; i++) {
arr[i] = new Item(Integer.parseInt(inputLine[k++]),
Integer.parseInt(inputLine[k++]));
}
System.out.println(String.format("%.6f", new Solution().fractionalKnapsack(w, arr, n)));
}
}
}
class Item {
int value, weight;
Item(int x, int y){
this.value = x;
this.weight = y;
}
}
class itemComparator implements Comparator<Item> {
@Override
public int compare(Item a, Item b) {
double r1 = (double)(a.value) / (double)(a.weight);
double r2 = (double)(b.value) / (double)(b.weight);
if(r1 < r2) {
return 1;
}
else if(r1 > r2) {
return -1;
}
else {
return 0;
}
}
}
class Solution {
double fractionalKnapsack(int w, Item arr[], int n) {
Arrays.sort(arr, new itemComparator());
int currW = 0;
double finalV = 0.0;
for(int i = 0; i < n; i++) {
if((currW + arr[i].weight) <= w) {
currW += arr[i].weight;
finalV += arr[i].value;
}
else {
int r = w - currW;
finalV += ((double)arr[i].value / (double)arr[i].weight) * (double)r;
break;
}
}
return finalV;
}
}