-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractionalKnapsack.java
More file actions
62 lines (49 loc) · 1.32 KB
/
FractionalKnapsack.java
File metadata and controls
62 lines (49 loc) · 1.32 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
import java.util.*;
class FractionalKnapsack {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int itemCount = in.nextInt();
int maxWeight = in.nextInt();
LinkedList<Item> items = new LinkedList<Item>();
for(int i = 0; i < itemCount; i++)
items.add(new Item(in.nextInt(), in.nextInt()));
Collections.sort(items, new ItemComparator());
int currWeight = 0;
double currCost = 0;
while(currWeight < maxWeight && !items.isEmpty()){
int remainingWeight = maxWeight - currWeight;
Item curr = items.poll();
if(curr.weight <= remainingWeight){
currWeight += curr.weight;
currCost += curr.cost;
}
if(curr.weight > remainingWeight){
currCost += remainingWeight*curr.ratio;
currWeight += remainingWeight;
}
}
System.out.printf("%.3f", currCost);
System.out.println();
}
}
class Item {
int cost;
int weight;
double ratio;
public Item(int cost, int weight){
this.cost = cost;
this.weight = weight;
ratio = ((double)cost)/weight;
}
}
class ItemComparator implements Comparator<Item> {
public int compare(Item first, Item second){
double difference = first.ratio - second.ratio;
if(difference > 0)
return -1;
else if(difference == 0)
return 0;
else
return 1;
}
}