-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractionalKnap.java
More file actions
128 lines (79 loc) · 3.02 KB
/
Copy pathFractionalKnap.java
File metadata and controls
128 lines (79 loc) · 3.02 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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.Scanner;
import java.util.TreeMap;
public class FractionalKnap {
public static void main(String[] args) {
// TODO Auto-generated method stub
// System.out.println("Jai Maa Manosha Maa");
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int capacity = scanner.nextInt();
int[] values = new int[n];
int[] weights = new int[n];
for (int i = 0; i < n; i++) {
values[i] = scanner.nextInt();
weights[i] = scanner.nextInt();
}
//System.out.println(getOptimalValue(capacity, values, weights));
System.out.println(getOptimalValue(capacity,values,weights)); }
private static double getOptimalValue(int capacity, int[] values, int[] weights) {
double value = 0;
double [] total = new double [values.length];
double [] c = new double [values.length];
TreeMap<Double,Integer> hm = new TreeMap<Double,Integer>();
Map<Integer,Integer> hm1 = new TreeMap<Integer,Integer>();
//write your code here
for(int i =0; i<values.length;i++)
{
total[i] = values[i]/weights[i];
hm.put(total[i],values[i]);
hm1.put(values[i], weights[i]);
}
NavigableSet nset=hm.descendingKeySet();
List<Integer> al = new ArrayList<Integer>();
for (Iterator<Double> iter=nset.iterator();iter.hasNext();) {
Double key = iter.next();
// System.out.println(key);
// System.out.println(hm.get(key) );
al.add(hm.get(key));
}
Integer v[]=al.toArray(new Integer[al.size()]);
//------------------------------------------------------------------------------------------------------------------//
for(int i=0;i<al.size();i++)
{
// hm1.containsKey(al.get(i));
// System.out.println("key" + al.get(i)+ "Value" + hm1.get(al.get(i)));
c[i] = hm1.get(al.get(i));
}
int t = 0;
for(int i=0;i<c.length;i++)
{
if(capacity>0)
{
if(c[i]>=capacity)
{
double temp = c[i]/capacity;
double totalvalue = v[i]/temp;
value = value + totalvalue;
capacity = (int) (capacity - c[i]);
}
}
if(c[i]<capacity)
{
capacity = (int) (capacity - c[i]);
value = value + v[i];
}
if(capacity == 0)
{
}
}
return value;
}
}