-
Notifications
You must be signed in to change notification settings - Fork 0
/
11027_PalindromicPermutation.cc
131 lines (114 loc) · 2.26 KB
/
11027_PalindromicPermutation.cc
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
123
124
125
126
127
128
129
130
131
/*
*
* Author : fcbruce <fcbruce8964@gmail.com>
*
* Time : Sun 11 Sep 2016 15:16:25
*
*/
#include <cstdio>
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <algorithm>
#include <ctime>
#include <cctype>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <set>
#define sqr(x) ((x)*(x))
#ifdef _WIN32
#define lld "%I64d"
#else
#define lld "%lld"
#endif
const int INF = 0x3f3f3f3f;
const long long INFLL = 0x3f3f3f3f3f3f3f3fll;
const double PI = acos(-1.0);
const double eps = 1e-10;
typedef long long LL;
typedef int itn;
const int maxn = 0;
const int maxm = 0;
char buffer[32];
int k;
int count[128];
char mid;
char left[32];
int length;
LL p[32];
bool ok()
{
length = strlen(buffer);
memset(count, 0, sizeof count);
for (int i = 0; i < length; i++) count[buffer[i]]++;
int cnt = 0;
for (int i = 'a'; i <= 'z'; i++) cnt += count[i] & 1;
LL res = p[length >> 1];
for (int i = 'a'; i <= 'z'; i++) res /= p[count[i] >> 1];
return cnt < 2 && k <= res;
}
long long calc_count(char c)
{
int len = 0;
count[c]--;
for (int i = 'a'; i <= 'z'; i++) len += count[i];
LL res = p[len];
for (int i = 'a'; i <= 'z'; i++) res /= p[count[i]];
count[c]++;
return res;
}
void rander()
{
mid = 'a';
for (; mid <= 'z' && !(count[mid] & 1); mid++) ;
if (mid > 'z') mid = 0;
for (int i = 'a'; i <= 'z'; i++) count[i] >>= 1;
for (int i = 0; i < (length >> 1); i++)
{
for (int j = 'a'; j <= 'z'; j++) if (count[j] > 0)
{
long long cnt = calc_count(j);
if (cnt >= k)
{
left[i] = j;
count[j]--;
break;
}
else
{
k -= cnt;
}
}
}
}
int main()
{
#ifdef FCBRUCE
freopen("/home/fcbruce/code/t", "r", stdin);
#endif // FCBRUCE
p[0] = 1;
for (int i = 1; i < 32; i++) p[i] = p[i - 1] * i;
int T_T, __ = 0;
scanf("%d", &T_T);
while (T_T--)
{
scanf("%s%d", buffer, &k);
printf("Case %d: ", ++__);
if (ok())
{
rander();
for (int i = 0; i < (length >> 1); i++) putchar(left[i]);
if (length & 1) putchar(mid);
for (int i = (length >> 1) - 1; i >= 0; i--) putchar(left[i]);
puts("");
}
else puts("XXX");
}
return 0;
}