-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathP941.cpp
64 lines (57 loc) · 1.44 KB
/
P941.cpp
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
#include <iostream>
#include <algorithm>
using namespace std;
typedef unsigned long long ul;
ul fac(int n) {
ul ret = 1;
for(int i = 2; i <= n; ++i)
ret *= i;
return ret;
}
ul permutations(string s, int begin, char skip) {
ul out = fac(-begin+(int)s.size()-1);
int rep = 1;
char prev = '_';
bool skipped = false;
for(unsigned int i = begin; i < s.size(); ++i) {
if(!skipped && s[i] == skip) {
skipped = true;
continue; // skip.
}
if(s[i] == prev)
++rep;
else {
out /= fac(rep);
rep = 1;
prev = s[i];
}
}
out /= fac(rep);
//cerr << "Permutations for " << s << ", start index " << begin << ", skipping " << skip << ": " << out << endl;
return out;
}
int main() {
int N;
cin >> N;
for(int cas = 1; cas <= N; ++cas) {
string s;
cin >> s;
ul rem, sub;
cin >> rem;
for(int i = 0; i < (int)s.size(); ++i) {
sort(s.begin()+i, s.end()); // Because of letter swapping.
int toSwapIndex = i;
while(toSwapIndex < (int)s.size() && (sub = permutations(s, i, s[toSwapIndex])) <= rem) {
//cerr << "Skipping letter " << s[toSwapIndex] << " in " << s << ", index " << toSwapIndex << ": " << rem << " -> " << (rem-sub) << endl;
rem -= sub;
do {
++toSwapIndex;
} while(toSwapIndex < (int)s.size()&& s[toSwapIndex-1] == s[toSwapIndex]);
}
if(toSwapIndex < (int)s.size()) {
swap(s[i], s[toSwapIndex]);
}
}
cout << s << endl;
}
}