- Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathQueue.java
More file actions
Latest commit
109 lines (96 loc) · 3.15 KB
/
Copy pathQueue.java
File metadata and controls
109 lines (96 loc) · 3.15 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
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
importstaticjava.util.Arrays.stream;
importstaticjava.util.stream.Collectors.toList;
importjava.io.BufferedReader;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.List;
importjava.util.stream.LongStream;
publicclassQueue {
privatestaticfinalBufferedReaderreader = newBufferedReader(
newInputStreamReader(System.in));
privatefinalintn;
privatefinalintk;
privatefinalint[] buckets;
privatefinalint[] queue;
privatefinalint[] values;
privatefinalboolean[] skip;
privatelongtotal;
privatelongcounter;
privatestaticfinallong[] factorial = LongStream.rangeClosed(0, 13)
.map(f -> f == 0 ? 1
: LongStream.rangeClosed(1, f).reduce(1L,
(x, y) -> x * y))
.toArray();
privatestaticfinalLong[][][] cache = newLong[13 + 1][13 + 1][13 + 1];
publicQueue(intn, intl, intr) {
this.n = n;
this.k = l - 1;
buckets = newint[n + 1];
skip = newboolean[n + 1];
queue = newint[l + r - 2];
values = newint[n - (l + r - 2) - 1 < 0 ? 0 : n - (l + r - 2) - 1];
skip[n] = true;
if (cache[n][l][r] != null) {
total = cache[n][l][r];
} else {
select(0);
cache[n][l][r] = total;
}
}
privatevoidselect(intpos) {
if (pos == queue.length) {
for (inti = 1, j = 0; i <= n; ++i) {
if (!skip[i]) {
values[j++] = i;
}
}
counter = 0;
count(0);
intnn = queue.length;
total += counter * factorial[nn] /
(factorial[k] * factorial[nn - k]);
return;
}
intstart = pos - 1 >= 0 ? queue[pos - 1] + 1 : 1;
for (inti = start; i < n; ++i) {
queue[pos] = i;
skip[i] = true;
select(pos + 1);
skip[i] = false;
}
}
privatevoidcount(intpos) {
if (pos == values.length) {
longpermutations = 1;
for (inti = 0; i < buckets.length; ++i) {
permutations *= factorial[buckets[i]];
}
counter += permutations;
return;
}
for (intbucket : queue) {
if (bucket > values[pos]) {
buckets[bucket]++;
count(pos + 1);
buckets[bucket]--;
}
}
}
publicstaticvoidmain(String[] args) throwsIOException {
intn = Integer.parseInt(reader.readLine().trim());
for (inti = 0; i < n; ++i) {
List<Integer> line = stream(reader.readLine().split(" "))
.filter(x -> !x.equals(""))
.map(Integer::parseInt)
.collect(toList());
intl = line.get(1);
intr = line.get(2);
if (l + r - 1 > 13) {
System.out.println(0);
} else {
Queueq = newQueue(line.get(0), l, r);
System.out.println(q.total);
}
}
}
}