-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTrace.java
102 lines (72 loc) · 1.73 KB
/
Trace.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
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
import java.io.*;
import java.util.*;
public class Trace {
static int n,s;
static int memo[][];
static int values[];
static int weights[];
static ArrayList<Integer> traced;
static int dp(int idx, int remw) {
if(idx==n) return 0;
if(memo[idx][remw]!=-1) return memo[idx][remw];
int result = 0;
int take = 0;
if(remw-weights[idx]>=0) {
take = dp(idx+1,remw-weights[idx]) + values[idx];
}
int leave = dp(idx+1,remw);
result = Math.max(take, leave);
memo[idx][remw] = result;
return result;
}
static void trace(int idx, int remw) {
if(idx==n) return;
int result = 0;
int take = -1;
if(remw-weights[idx]>=0) {
take = dp(idx+1,remw-weights[idx]) + values[idx];
}
int leave = dp(idx+1,remw);
result = Math.max(take, leave);
if(result==take) {
traced.add(idx);
trace(idx+1,remw-weights[idx]);
}
else {
//not adding the index
trace(idx+1,remw);
}
}
/* Test Input
typical knapsack input of:
numberofitems sizeofsack
valuei weighti
4 12
100 10
70 4
50 6
10 12
*/
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = sc.nextInt();
s = sc.nextInt();
memo = new int[n+1][s+1];
values = new int[n+1];
weights = new int[n+1];
traced = new ArrayList<>();
for(int e[] : memo)
Arrays.fill(e, -1);
for(int i=0;i<n;i++) {
values[i] = sc.nextInt();
weights[i] = sc.nextInt();
}
dp(0,s);
pw.println(memo[0][s]);
trace(0,s);
for(Integer x : traced)
pw.println(x);
pw.close();
}
}