forked from Dishakumra/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
knapsack.java
59 lines (56 loc) · 1016 Bytes
/
knapsack.java
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
import java.util.*;
class knapsack
{
public static void swap(float arr[],int i,int j)
{
float temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
float w[]=new float[size];
float p[]=new float[size];
float pw[]=new float [size];
for(int i=0;i<size;i++)
w[i]=sc.nextFloat();
for(int i=0;i<size;i++)
p[i]=sc.nextFloat();
float capacity=sc.nextFloat();
for(int i=0;i<size;i++)
pw[i]=p[i]/w[i];
for(int j=0;j<size;j++)
{
for(int i=0;i<size-1;i++)
{
if(pw[i]<pw[i+1])
{
swap(pw,i,i+1);
swap(p,i,i+1);
swap(w,i,i+1);
}
}
}
float currentp=0;
for(int i=0;i<size;i++)
{
if(capacity==0)
break;
else if(capacity>=w[i])
{
currentp+=pw[i]*w[i];
// System.out.println(pw[i]);
capacity-=w[i];
}
else
{
currentp+=pw[i]*capacity;
//System.out.println(pw[i]);
capacity=0;
}
}
System.out.println(currentp);
}
}