-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCD_backtracking.java
97 lines (80 loc) · 2.5 KB
/
CD_backtracking.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
import java.io.*;
import java.util.StringTokenizer;
public class CD_backtracking {
private static InputReader input = new InputReader(System.in);
private static PrintWriter output = new PrintWriter(System.out);
public static void main(String[] args) {
Problem CD_backtracking = new Problem();
CD_backtracking.Solve();
output.close();
}
static class Problem {
int M, n;
int[] t;
int answer;
int best;
void Solve() {
while(input.Ready()) {
M = input.nextInt();
n = input.nextInt();
t = new int[n];
for (int i = 0; i < n; ++i) {
t[i] = input.nextInt();
}
answer = 0;
best = 0;
back(0,0, 0);
for (int i = 0; i < n; ++i) {
if(isOn(answer, i)) {
output.printf("%d ", t[i]);
}
}
output.printf("sum:%d\n", best);
}
}
boolean isOn (int mask, int i) {
return ((mask >> i) & 1) == 1;
}
int onBit (int mask, int i) {
return (mask | (1 << i));
}
void back (int i, int mask, int current) {
if(current <= M && best < current) {
best = current;
answer = mask;
}
if(i < n) {
back(i+1, mask, current);
back(i+1, onBit(mask, i), current + t[i]);
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public boolean Ready() {
try {
return reader.ready();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}