FZU 1571 排列的字典序问题

Description

n个元素{1,2,...,n}有n!个不同的排列。将这n!个排列按字典序排列并编号为0,1,...,n!-1。每个排列的编号为其字典序值。例如,当n=3时,6个不同排列的字典序值如下:

字典序值012345
排列123132213231312321

给定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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值