-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractional_Knapsack.java
More file actions
50 lines (49 loc) · 1.09 KB
/
Copy pathFractional_Knapsack.java
File metadata and controls
50 lines (49 loc) · 1.09 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
import java.io.IOException;
import java.util.Scanner;
class Greedy_Knapsack_Problem
{
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int i,j=0,m;
float sum=0,max=0;
//Number of Item
int n=sc.nextInt();
int a[][]=new int [2][n];
//weight in Knapsack
for(i=0;i<n;i++)
{
a[0][i]=sc.nextInt();
}
//Value in Kanpsack
for(i=0;i<n;i++)
{
a[1][i]=sc.nextInt();
}
//Max Weight of Knapsack
m=sc.nextInt();
while(m>=0)
{
max=0;
for(i=0;i<n;i++)
{
if(((float)a[1][i]/((float)a[0][i]))>max)
{
max=((float)a[1][i]/((float)a[0][i]));
j=i;
}
}
if(a[0][j]>m)
{
sum+=m*max;
m=-1;
}
else
{
sum+=a[1][j];
m-=a[0][j];
a[1][j]=0;
}
}
System.out.println(sum);
}
}