#include <cstdio> #include <algorithm> #include <cstring> #include <string> #include <iostream> using namespace std; int n; char str[50]; char ans[50]; string half; int num[30]; int len; int mid; int cantor[16]; void init(int n){ cantor[1] = 1; cantor[0] = 1; for (int i = 2; i <= n; i++)cantor[i] = cantor[i - 1] * i; } void doit(int n, char *res, string& half, int* num, int* cantor){ int ll = 0; int m = 0; while (ll < (len)/2){ int i = 0; while (1){ int k, b; while (num[half[i] - 'a']<=0)i++; k = num[half[i] - 'a'] - 1; b = cantor[num[half[i] - 'a'] - 1]; for (int j = 0; j < half.length(); j++)if (j != i && num[half[j] - 'a']>0){ k += num[half[j] - 'a']; b*= cantor[num[half[j] - 'a']]; } b = cantor[k]/b; // if (i == 26)b = 0; if (b + m >= n){ res[ll++] = half[i]; num[half[i] - 'a']--; break; } else { m += b; i++; } } } res[ll] = 0; return; } int main(){ init(15); int t; scanf("%d", &t); for (int ca = 1; ca<= t; ca++){ scanf("%s %d", str, &n); printf("Case %d: ", ca); memset(num, 0, sizeof(num)); len = strlen(str); for (int i = 0; i < len; i++){ num[str[i] - 'a']++; } int c1 = 0; for (int i = 0; i < 26; i++){ if (num[i]%2){ mid = i; c1++; } num[i] /= 2; } if (c1 > 1){ printf("XXX\n"); continue; } int c2 = 1; int c3 = 0; for (int i = 0; i < 26; i++){ c3 += num[i]; c2 *= cantor[num[i]]; } c2 = cantor[c3]/c2; if (n>c2){ printf("XXX\n"); continue; } half.clear(); for (int i = 0; i < 26; i++)if (num[i]){ half += char(i+'a'); } doit(n, ans, half, num, cantor); int ll = strlen(ans); if (len&1){ ans[ll++] = mid + 'a'; } for (; ll < len; ll++){ ans[ll] = ans[len-ll-1]; } ans[len] = 0; puts(ans); } return 0; }
UVA 11027 Palindromic Permutation
最新推荐文章于 2021-06-24 23:24:09 发布