Accept: 310 Submit: 1095
Time Limit: 1000 mSec Memory Limit : 32768 KB
Problem 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
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long int ll;
ll Fac[15];
void FUN(){
Fac[0] = Fac[1] = 1;
for(int i=2; i<=13; i++)
Fac[i] = i*Fac[i-1];
}
int book[100];
int main(){
FUN();
ll ans = 0;
int N;
int a[100];
scanf("%d",&N);
for(int i=1; i<=N; i++)
scanf("%d",&a[i]);
int num,count;
for(int i=1; i<N; i++){
num = a[i];
count = 0;
for(int j=i+1; j<=N; j++){
if(a[j]<num)
count++;
}
ans += count*Fac[N-i];
}
printf("%I64d\n",ans);
next_permutation(a+1,a+1+N);
for(int i=1; i<=N; i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long int ll;
ll Fac[15];
void FUN(){
Fac[0] = Fac[1] = 1;
for(int i=2; i<=13; i++)
Fac[i] = i*Fac[i-1];
}
int book[100];
int main(){
FUN();
ll ans = 0;
int N;
int a[100];
scanf("%d",&N);
for(int i=1; i<=N; i++)
scanf("%d",&a[i]);
int num,count;
for(int i=1; i<N; i++){
num = a[i];
count = 0;
for(int j=i+1; j<=N; j++){
if(a[j]<num)
count++;
}
ans += count*Fac[N-i];
}
printf("%I64d\n",ans);
next_permutation(a+1,a+1+N);
for(int i=1; i<=N; i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}