-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkth_permutation.cpp
59 lines (55 loc) · 1.23 KB
/
kth_permutation.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
#include <bits/stdc++.h>
#define lli long long int
#define mod 1000000007
using namespace std;
void factorial( vector<int>& fact)
{
fact[1] = 1;
for ( int i =2; i <= 10; ++ i )
fact[i] = i*fact[i-1];
}
string getPermutation(string res, int k, vector<int>& fact) {
int n = res.size();
string ans = "";
while (n > 1)
{
int q = k / fact[n-1];
if( k % fact[n-1] == 0 )
{
ans += res[q-1];
res.erase(q-1,1);
reverse(res.begin(),res.end());
ans += res;
return ans;
}
else
{
ans += res[q];
res.erase(q,1);
}
k -= q*fact[n-1];
n--;
}
ans += res;
return ans ;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
vector<int> fact(11);
factorial(fact);
int t;
cin>>t;
while(t--)
{
string s;
cin>>s;
sort(s.begin(), s.end());
for(int i = 1; i <= fact[s.size()]; ++i)
cout<<getPermutation(s,i,fact)<<" ";
cout<<"\n";
}
return 0;
}