-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShipRoutes.java
78 lines (60 loc) · 1.89 KB
/
ShipRoutes.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
import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class ShipRoutes
{
private static int n;
private static Map<String, BigInteger> cache;
private static BigInteger bfs(int params[], int prev)
{
int a = (prev + 1) % 3;
int b = (prev + 2) % 3;
int val_a = params[a];
int val_b = params[b];
int val_c = params[prev];
String key = ""+val_a+" "+val_b+" "+val_c+" "+prev;
if (cache.containsKey(key)) {
return cache.get(key);
}
BigInteger result = BigInteger.ZERO;
if (params[a]==0 && params[b] == 0) {
if (prev != 0 && params[prev] == 0) {
// warn "HIT! ".join(", ",0, @$path,0);
return BigInteger.ONE;
}
else {
return BigInteger.ZERO;
}
}
if (params[a] > 0) {
params[a]--;
result = result.add(bfs(params, a));
params[a]++;
}
if (params[b] > 0) {
params[b]--;
result = result.add(bfs(params, b));
params[b]++;
}
cache.put(key, result);
return result;
}
private static BigInteger factorial(int n)
{
BigInteger result = BigInteger.ONE;
while(n>0) {
result = result.multiply(BigInteger.valueOf(n));
n--;
}
return result;
}
public static void main(String[] argv) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
n = in.nextInt();
cache = new HashMap<>();
BigInteger f = factorial(n-1);
BigInteger g = f.multiply(BigInteger.valueOf(n));
System.out.println(""+bfs(new int[]{n-1,n,n},0).multiply(f).multiply(g).multiply(g).divide( BigInteger.valueOf(2) ));
}
}