Skip to content

Instantly share code, notes, and snippets.

@nichtemna
Created August 15, 2016 12:27
Show Gist options
  • Save nichtemna/36eada5deb130d9279a89e0964a1470e to your computer and use it in GitHub Desktop.
Save nichtemna/36eada5deb130d9279a89e0964a1470e to your computer and use it in GitHub Desktop.
Knapsack problem
A thief finds much more loot than his bag can fit.
Help him to find the most valuable combination of items assuming that
any fraction of a loot item can be put into his bag.
Task. The goal of this code problem is to implement an algorithm for the fractional knapsack problem.
Input Format. The first line of the input contains the number n of items and the capacity W of a knapsack.
The next n lines define the values and weights of the items. The i-th line contain integers v and w —
the value and the weight of i-th item, respectively.
Constraints. 1 ≤ n ≤ 10^3
0 ≤ W ≤ 2 · 10^6
0 ≤ v ≤ 2 · 10^6
0 < w ≤ 2 · 10^6
for all 1 ≤ i ≤ n.
All the numbers are integers.
Output Format. Output the maximal value of fractions of items that fit into the knapsack.
Input:
3 50
60 20
100 50
120 30
Output:
180.0000
public class Loot {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int w = scanner.nextInt();
Map<Integer, Integer> values = new TreeMap<>();
while (scanner.hasNextInt()) {
int value = scanner.nextInt();
int weight = scanner.nextInt();
values.put(value, weight);
}
double max = countMax(w, values);
System.out.println(max);
}
private static double countMax(int w, Map<Integer, Integer> values) {
Map<Integer, Integer> newMap = new TreeMap(new MyComparator(values));
newMap.putAll(values);
return countMaxFromMap(w, newMap);
}
private static double countMaxFromMap(int w, Map<Integer, Integer> values) {
double max = 0;
int left = w;
for (Map.Entry<Integer, Integer> entry : values.entrySet()) {
if (left == 0) {
break;
}
int value = entry.getKey();
int weight = entry.getValue();
int fit;
if (weight > left) {
fit = left;
} else {
fit = weight;
}
max += (double) fit * ((double) value / (double) weight);
left -= fit;
}
return max;
}
static class MyComparator implements Comparator {
Map<Integer, Integer> map;
public MyComparator(Map map) {
this.map = map;
}
public int compare(Object o1, Object o2) {
int v1 = (int) o1;
int w1 = map.get(o1);
int v2 = (int) o2;
int w2 = map.get(o2);
return (double) v2 / (double) w2 > (double) v1 / (double) w1 ? 1 : -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment