Description
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}的一个排列,计算出这个排列的字典序值,以及按字典序排列的下一个排列。
Input
输入包括多组数据。
每组数据的第一行是元素个数n(1<=n<=13),接下来1行是n个元素{1,2,...,n}的一个排列。
Output
对于每组数据,输出两行,第一行是字典序值,第2行是字典序排列的下一个排列。
Sample Input
8 2 6 4 5 8 1 7 3
Sample Output
8227 2 6 4 5 8 3 1 7
其实就是一个康托展开和逆康托展开...
STL做法(以前的 现在觉得好怪):
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
int input[15];
ll fact(int n)
{
ll res=1;
for(int i=2;i<=n;i++)
{
res*=i;
}
return res;
}
int main()
{
int a;
while(cin>>a)
{
ll res=0;
for(int i=0;i<a;i++)
cin>>input[i];
for(int i=0;i<a;i++)
{
int cou=input[i]-1;
for(int j=0;j<i;j++)
if(input[j]<input[i])
cou--;
res+=cou*fact(a-i-1);
}
cout<<res<<endl;
next_permutation(input,input+a);
for(int i=0;i<a;i++)
{
if(i)
cout<<' ';
cout<<input[i];
}
cout<<endl;
}
return 0;
}
逆康托展开:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <queue>
#include <map>
#include <string>
#include <stack>
#include <bitset>
#include <vector>
using namespace std;
int a[20], fact[20];
int main() {
#ifdef LOCAL
freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
#endif
int n;
while(~scanf("%d", &n)) {
fact[0] = 1;
vector<int> num;
num.clear();
for(int i = 0; i < n; i++) {
scanf("%d", &a[i]);
num.push_back(i + 1);
if(i) fact[i] = i * fact[i - 1];
}
int X = 0;
for(int i = 0; i < n; i++) {
int ran = 0;
for(int j = i; j < n; j++) {
if(a[j] < a[i]) ran++;
}
X += fact[n - 1 - i] * ran;
}
printf("%d\n", X);
X++;
for(int i = 0; i < n; i++) {
int quot = X / fact[n - 1 - i], rem = X % fact[n - 1 - i];
a[i] = num[quot];
num.erase(num.begin() + quot);
X = rem;
}
for(int i = 0; i < n; i++) {
printf("%d%c", a[i], i == n - 1 ? '\n' : ' ');
}
}
return 0;
}