-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gentlements.java
127 lines (97 loc) · 3.02 KB
/
Gentlements.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
public class Gentlements
{
public static int realWeight;
public static int correctWeights[];
private static Map<String,Result> cache;
public static Result funcCached(int left, int right, int coin) {
String key = ""+left+"_"+right+"_"+coin;
if (!cache.containsKey(key)) {
cache.put(key, func2(left, right, coin));
}
return new Result(cache.get(key));
}
public static class Result {
List<Integer> cards;
int ways;
public Result(List<Integer> cards, int ways) {
if (cards != null) {
this.cards = new LinkedList<>();
this.cards.addAll(cards);
}
else {
cards = null;
}
this.ways = ways;
}
public Result (Result r) {
this(r.cards, r.ways);
}
public String toString() {
if (cards == null) {
return "[null]";
}
return Arrays.toString(cards.toArray());
}
public void print() {
warn(toString());
}
}
public static Result func2(int left, int right, int coin) {
//warn("l="+left+" r="+right+" c="+coin );
if (left == 0 && right == 0) {
return new Result(new LinkedList<>(), 1);
}
else if (left < 0 || right < 0) {
return new Result(null, 0);
}
else if (coin > correctWeights.length - 1) {
return new Result(null, 0);
}
Result lr = funcCached(left - correctWeights[coin], right, coin+1);
Result rl = funcCached(left, right - correctWeights[coin], coin+1);
if (lr.cards != null) {
lr.cards.add(coin+1);
lr.ways += rl.ways;
return lr;
}
else {
if (rl.cards != null) {
rl.ways += lr.ways;
return rl;
}
}
return new Result(null, 0);
}
public static void warn(String s) {
System.out.println(s);
}
public static void main(String[] argv) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
realWeight = in.nextInt();
int n = in.nextInt();
correctWeights = new int[n];
int sum= 0;
for (int i = 0; i < n; i++) {
correctWeights[i] = in.nextInt();
sum += correctWeights[i];
}
cache = new HashMap<>();
Result r = funcCached(sum - realWeight,realWeight,0);
if (r.cards != null) {
if (r.ways > 1) {
out.println("-1");
}
else {
out.println(r.cards.stream().sorted().map(e -> e.toString()).collect(Collectors.joining(" ")));
}
}
else {
out.println( "0" );
}
out.flush();
}
}