-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamicknapsack.java
More file actions
52 lines (40 loc) · 1.26 KB
/
dynamicknapsack.java
File metadata and controls
52 lines (40 loc) · 1.26 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
public class dynamicknapsack {
static int[][] K;
public static int knap(int n , int[] W , int[] V , int maxW) {
for (int i = 0; i < n + 1; i++)
for (int j = 0; j < maxW + 1; j++)
{
if (i == 0 || j == 0)
K[i][j] = 0;
else if (j - W[i - 1] < 0)
K[i][j] = K[i - 1][j];
else
K[i][j] = Math.max(V[i - 1] + K[i - 1][j - W[i - 1]] , K[i - 1][j]);
}
return K[n][maxW];
}
public static void main(String[] args) {
/*
int n = 8;
int[] W = {1 , 3 , 4 , 3 , 3 , 1 , 5 , 10};
int[] V = {2 , 9 , 3 , 8 , 10 , 6 , 4 , 10};
int maxW = 15;
K = new int[n + 1][maxW + 1];
long start = System.currentTimeMillis();
System.out.println(knap(n , W , V , maxW));
long end = System.currentTimeMillis();
System.out.println((end - start) / 1000.0 + " seconds");
*/
/*
int n = 30;
int[] W = {1 , 3 , 4 , 3 , 3 , 1 , 5 , 10 , 1 , 3 , 4 , 3 , 3 , 1 , 5 , 10 , 1 , 3 , 4 , 3 , 3 , 1 , 5 , 10 , 1 , 3 , 4 , 3 , 3 , 1};
int[] V = {2 , 9 , 3 , 8 , 10 , 6 , 4 , 10 , 2 , 9 , 3 , 8 , 10 , 6 , 4 , 10 , 2 , 9 , 3 , 8 , 10 , 6 , 4 , 10 , 1 , 3 , 9 , 3 , 8 , 6};
int maxW = 85;
K = new int[n + 1][maxW + 1];
long start = System.currentTimeMillis();
System.out.println(knap(n , W , V , maxW));
long end = System.currentTimeMillis();
System.out.println((end - start) / 1000.0 + " seconds");
*/
}
}