题目描述
n个元素{1,2,…, n }有n!个不同的排列。将这n!个排列按字典序排列,并编号为0,1,…,n!-1。每个排列的编号为其字典序值。例如,当n=3时,6 个不同排列的字典序值如下:
0 1 2 3 4 5
123 132 213 231 312 321
任务:给定n 以及n 个元素{1,2,…, n }的一个排列,计算出这个排列的字典序值,以及按字典序排列的下一个排列。
输入
第1 行是元素个数n(n < 15)。接下来的1 行是n个元素{1,2,…, n }的一个排列。
输出
第一行是字典序值,第2行是按字典序排列的下一个排列。
样例
- Input
8
2 6 4 5 8 1 7 3 - output
8227
2 6 4 5 8 3 1 7
思路
- 康托展开:设某个排列{x0,x1,x2…x(n-1)}的对应键值为k,则
k=a[0]*(n-1)!+a[1]*(n-2)!+...+a[n-1]*0!
,其中a[i]表示x[i]在i~n-1中的升序位置,同时也可以得知该排列在所有排列中是第k+1个。 - 康托逆展开:已知键值k求排列。通过上面的式子,我们令i从(n-1)到0,每次取
t=k/(i!)
,显然i后面所有式子加起来都没有i!大,故得到的t就表示这个位置应该填的数是在剩下还没有填的数的升序位置,然后用k/=(i!)
去找下一位。
Code
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
| #include<bits/stdc++.h> #define INIT(a,b) memset(a,b,sizeof(a)) #define LL long long using namespace std; const int inf=0x3f3f3f3f; const int maxn=1e2+7; const int mod=1e9+7; LL jc[maxn]; LL Cantor(LL *a,LL n){ LL ans=0,c=0; for(int i=0;i<n;i++){ c=0; for(int j=i+1;j<n;j++) if(a[i]>a[j])c++; ans+=c*jc[n-1-i]; } return ans; } void DeCantor(LL num,LL n){ vector<LL>cnt; for(int i=1;i<=n;i++) cnt.push_back(i); LL ans[maxn],tem; for(int i=n-1;i>=0;i--){ tem=num/jc[i]; num%=jc[i]; printf("%lld ",cnt[tem]); cnt.erase(cnt.begin()+tem); } printf("\n"); } int main(){ int n; jc[0]=1; for(int i=1;i<=15;i++)jc[i]=jc[i-1]*i; while(~scanf("%d",&n)){ LL a[maxn]; for(int i=0;i<n;i++) scanf("%lld",&a[i]); LL next=Cantor(a,n); printf("%lld\n",next); DeCantor((next+1)%jc[n],n); }
return 0; }
|