-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringer.java
More file actions
122 lines (81 loc) · 2.75 KB
/
Copy pathStringer.java
File metadata and controls
122 lines (81 loc) · 2.75 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/**
Written by Mike O'Beirne (michael.obeirne@gmail.com)
Passes ACM LiveJudge.
**/
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Scanner;
public class Stringer {
static HashMap<Integer, BigInteger> factorial = new HashMap<Integer, BigInteger>();
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int numLetters = in.nextInt();
while (numLetters != 0) {
long index = in.nextLong() + 1;
int totalLetters = 0;
int[] letters = new int[numLetters + 1];
// Input letter counts
for (int i = 0; i < numLetters; i++) {
letters[i] = in.nextInt();
totalLetters += letters[i];
}
letters[numLetters] = totalLetters;
System.out.println(solve(index, letters, ""));
numLetters = in.nextInt();
}
}
static String solve(long index, int[] letters, String ans) {
if (letters[letters.length - 1] == 0) {
return ans;
}
// We're guaranteed to use a letter
letters[letters.length - 1]--;
// Consider each available letter and
// the number of words using the remaining letters
// attached to the current
for (int i = 0; i < letters.length - 1; i++) {
if (letters[i] == 0) {
continue;
}
letters[i]--;
char current = (char) ('a' + i);
// Calculate the number of words using the remaining letters
long possibleWords = numWords(letters[letters.length - 1],
letters);
// If we've found the range of words it's in...
if (index - possibleWords <= 0) {
return solve(index, letters, ans + current);
}
// Return to previous state of letters
// and subtract from our index
else {
index -= possibleWords;
letters[i]++;
}
}
return "Error! Shouldn't reach this point!";
}
static long numWords(int N, int[] letters) {
BigInteger ans = factorial(N);
for (int i = 0; i < letters.length - 1; i++) {
ans = ans.divide(factorial(letters[i]));
}
return ans.longValue();
}
static BigInteger factorial(int N) {
if (N == 0) {
return BigInteger.ONE;
}
if (factorial.containsKey(N)) {
return factorial.get(N);
}
else {
BigInteger current = BigInteger.ONE;
for (int i = 1; i <= N; i++) {
current = current.multiply(BigInteger.valueOf(i));
factorial.put(i, current);
}
return current;
}
}
}