File tree Expand file tree Collapse file tree 2 files changed +68
-0
lines changed
src/algorithms/continuous_knapsack Expand file tree Collapse file tree 2 files changed +68
-0
lines changed Original file line number Diff line number Diff line change 1+ package algorithms .continuous_knapsack ;
2+
3+ import java .util .Arrays ;
4+ import java .util .Scanner ;
5+
6+ public class Main {
7+ public static void main (String [] args ) {
8+ Scanner scanner = new Scanner (System .in );
9+ int subjectsNumber = scanner .nextInt ();
10+ int knapsackCapability = scanner .nextInt ();
11+ double currentValue = 0 ;
12+ int currentWeight = 0 ;
13+ Subject [] subjects = new Subject [subjectsNumber ];
14+ for (int i = 0 ; i < subjectsNumber ; i ++) {
15+ int cost = scanner .nextInt ();
16+ int weight = scanner .nextInt ();
17+ subjects [i ] = new Subject (cost , weight );
18+ }
19+ Arrays .sort (subjects , (a , b ) -> b .getUnitValue ().compareTo (a .getUnitValue ()));
20+ for (Subject subject : subjects ) {
21+ if (currentWeight == knapsackCapability ) {
22+ break ;
23+ }
24+ int maxItemWeight = subject .getWeight ();
25+ if (maxItemWeight > knapsackCapability - currentWeight ) {
26+ maxItemWeight = knapsackCapability - currentWeight ;
27+ }
28+ currentValue += maxItemWeight * subject .getUnitValue ();
29+ currentWeight += maxItemWeight ;
30+ }
31+ System .out .println (String .format ("%.3f" , currentValue ));
32+ }
33+ }
Original file line number Diff line number Diff line change 1+ package algorithms .continuous_knapsack ;
2+
3+ public class Subject {
4+ private Integer cost ;
5+ private Integer weight ;
6+ private Double unitValue ;
7+
8+ public Subject (int cost , int weight ) {
9+ this .cost = cost ;
10+ this .weight = weight ;
11+ unitValue = (double )cost / weight ;
12+ }
13+
14+ public Integer getCost () {
15+ return cost ;
16+ }
17+
18+ public void setCost (Integer cost ) {
19+ this .cost = cost ;
20+ unitValue = (double )cost / weight ;
21+ }
22+
23+ public Integer getWeight () {
24+ return weight ;
25+ }
26+
27+ public void setWeight (Integer weight ) {
28+ this .weight = weight ;
29+ unitValue = (double )cost / weight ;
30+ }
31+
32+ public Double getUnitValue () {
33+ return unitValue ;
34+ }
35+ }
You can’t perform that action at this time.
0 commit comments