排列的字典序问题

#include "iostream"
#include "algorithm"
#include "fstream"
using namespace std;

//求n的阶乘
int factorial(int n)
{
    int f = 1;
    for(int i=2; i<=n; i++)
        f *= i;
    return f;
}


/*
2 6 4 5 8 1 7 3

tot=0;
比2小的数有1个,则 tot+=1*7!;
比6小的数有4个,则 tot+=4*6!;
比4小的数有2个,则 tot+=2*5!;
比5小的数有2个,则 tot+=2*4!;
比8小的数有3个,则 tot+=3*3!;
比1小的数有0个,则 tot+=0*2!;
比7小的数有1个,则 tot+=1*1!;
比3小的数没有;

 */
//返回a[0,n-1]的字典序
int num(int a[], int n)
{
    int count = 0;
    int *b = new int[n];
    copy(a, a+n, b);
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<i; j++)
            if(b[j] < b[i])
                b[i]--;
        b[i]--;
        count += factorial(n-i-1) * b[i];
    }
    return count;
}

/*
如何得到2 6 4 5 8 1 7 3的下一个排列?
    1,从尾部往前找第一个P(i-1) < P(i)的位置
            2 6 4 4 5 8 1 <- 7 <- 3
        最终找到1是第一个变小的数字,记录下1的位置i-1
    2,从尾部往前找到第一个大于1的数
            2 6 4 4 5 8 1 7 3 <-
        最终找到3的位置,记录位置为m
    3,交换位置i-1和m的值
            2 6 4 4 5 8 3 7 1 
    4,倒序i位置后的所有数据
            2 6 4 4 5 8 3 1 7 

  */
//得到a[0,n-1]的下一个排列
void nextPerm(int a[], int n)
{
    int min, max;
    for(int i=n-1; i>=0; i--) //1
        if(a[i-1]<a[i])
        {
            min = i-1;
            break;
        }

    for(i=n-1; i>=0; i--) //2
        if(a[i]>a[min])
        {
            max = i;
            break;
        }

    swap(a[min], a[max]); //3

    reverse(a+min+1, a+n); //4

}

int main()
{
    ifstream fin("dict.txt");
    int n;
    fin >> n;
    cout << "元素个数:" << n;
    int *a = new int[n];
    cout << "\n当前字符排列为:";
    for(int i=0; i<n; i++)
    {
        fin >> a[i];
        cout << a[i] << " ";
    }
    int count = num(a, n);
    cout << "\n当前字符串字典序为:" << count << endl;
    nextPerm(a, n);
    cout << "下一排列为:";
    for(i=0; i<n; i++)
        cout << a[i] << " ";
    cout << endl;
    fin.close();
    return 0;
} 

这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值