-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLOJ-1060.cpp
69 lines (69 loc) · 1.79 KB
/
LOJ-1060.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
65
66
67
68
69
#include<bits/stdc++.h>
using namespace std;
char s[22];
unsigned long long n,l,f[21],frq[27];
void fact(){
f[0]=1;
for(unsigned long long i=1;i<=20;i++)f[i]=i*f[i-1];
return;
}
void path(int mask,int ii,unsigned long long lim){
if(ii==l)return;
if(lim==1){
for(int i=0;i<l;i++){
if(!(mask&(1<<i)))cout<<s[i];
}return;
}
unsigned long long x=f[l-ii-1];
int mark=0;
for(int i=0;i<l;i++){
if(!(mask&(1<<i)) && !(mark&(1<<i))){
x/=f[frq[s[i]-'a']];
mark|=(1<<i);
}
}
unsigned long long a=lim/x;
mark=0;
int p=0;
if((a*x)==lim){
for(int i=l-1;i>=0;i--){
if(!(mask&(1<<i))){
cout<<s[i];
}
}
return;
}
for(int i=0;i<l;i++){
if(!(mask&(1<<i))){
if(p==a){
cout<<s[i];
path(mask|(1<<i),ii+1,lim-a*x);
return;
}
p++;
}
}
return;
}
int main() {
int t;
fact();
scanf("%d",&t);
for(int z=1; z<=t; z++) {
getchar();
scanf("%s %llu",s,&n);
l=strlen(s);
sort(s,s+l);
memset(frq,0,sizeof(frq));
for(int i=0;i<l;i++)frq[s[i]-'a']++;
unsigned long long x=f[l];
for(int i=0;i<26;i++)x/=f[frq[i]];
if(n>x){
cout<<"Case "<<z<<": Impossible\n";
continue;
}
path(0,0,n);
puts("");
}
return 0;
}