-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathCompleteTreeLabeling.java
76 lines (67 loc) · 2.42 KB
/
CompleteTreeLabeling.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
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
class CompleteTreeLabeling {
private static final BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
private static List<BigInteger> expand(int n, int upto) {
List<BigInteger> res = new ArrayList<BigInteger>();
for (int i = n; i > upto; --i) {
res.add(BigInteger.valueOf(i));
}
return res;
}
private static BigInteger mult(List<BigInteger> l) {
return l.stream().reduce(BigInteger.ONE, (x, y) -> x.multiply(y));
}
private static BigInteger choose(int n, int k) {
List<BigInteger> numerator = expand(n, (n - k));
List<BigInteger> denominator = expand(k, 0);
Iterator<BigInteger> it = denominator.iterator();
while (it.hasNext()) {
if (numerator.remove(it.next())) {
it.remove();
}
}
return mult(numerator).divide(mult(denominator));
}
private static BigInteger count(BigInteger base, int treeSize, int k,
int h) {
if (h == 1) {
return base;
}
int subtreeSize = (treeSize - 1) / k;
BigInteger subtreeCount = count(base, subtreeSize, k, h - 1);
BigInteger count = base;
for (int i = subtreeSize - 1; i <= treeSize - 2; i += subtreeSize) {
count = count.multiply(subtreeCount)
.multiply(choose(i, subtreeSize - 1));
}
return count;
}
private static BigInteger solve(int k, int h) {
if (k == 1) {
return BigInteger.ONE;
}
int pow = 1;
for (int i = 0; i < h + 1; ++i) {
pow *= k;
}
return count(mult(expand(k, 0)), (pow - 1) / (k - 1), k, h);
}
public static void main(String[] args) throws IOException {
String currentLine;
while ((currentLine = reader.readLine()) != null) {
List<Integer> input = stream(currentLine.trim().split(" "))
.filter(x -> !x.equals("")).map(Integer::parseInt)
.collect(toList());
System.out.println(solve(input.get(0), input.get(1)));
}
}
}