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
第1 行是元素个数n(n < 15)。接下来的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<iostream>
#include<algorithm>
using namespace std;

//计算阶乘
int factorial(int n)
{
    if (n <= 1) return 1;
    return factorial(n - 1)*n;
}
//字典序列问题
//计算当前排列在 字典序列中的位置(从0开始)
int order(int *data, int n)
{
    int re = 0;
    for (int i = 0; i<n; i++)
    {
        int m = data[i], count = 0;
        for (int j = i; j<n; j++)
            if (m>data[j]) count++;
        re += count*factorial(n - i - 1);
    }
    return re;
}

int main()
{
    int *data = new int[1000];
    int n;
    while (cin >> n)
    {
        for (int i = 0; i<n; i++) cin >> data[i];
        cout << order(data, n) << endl;
        next_permutation(data, data + n);
        for (int i = 0; i<n; i++)
        {
            cout << data[i] << " ";
        }
        cout << endl;
    }
    return 0;
}

clipboard.png


Light
11 声望0 粉丝