HDOJ 1027 Ignatius and the Princess II

NextPermutation优化
本文介绍了一个基于STL函数库next_permutation的优化方法,通过在调用next_permutation之前进行特定优化来减少不必要的操作,从而提高了求解特定排列问题的效率。

         如果知道STL函数库中的next_permutation函数,此题丝毫没有难度。然后可以反复调用此函数即可。我在此基础上做了优化。因为第N!th的序列都相当于将序列的后n位逆序排列。所以可以在调用next_permutation函数之前,优化前N!次调用(N!<nth)。

#include <algorithm>
#include <vector>
using namespace std;
#include<stdio.h>
int main()
{
    //freopen("Ignatius and the Princess II.txt","r",stdin);
    int seqLength,seqNumber;
    while(scanf("%d%d",&seqLength,&seqNumber)!=EOF)
    {
        vector<int> array;
        int sum=1,start=1;
        while(seqNumber>=sum*(start+1))
        {
            start++;
            sum*=start;
        }
        for (int i=1;i<=seqLength;i++)
            array.push_back(i);
        int reverseStart=seqLength-start;
        reverse(array.begin()+reverseStart,array.end());
        for (int i=sum+1;i<=seqNumber;i++)
            next_permutation(array.begin(),array.end());
        for (int i=0;i<seqLength-1;i++)
            printf("%d ",array[i]);
        printf("%d\n",array[seqLength-1]);
    }
    return 0;
}

转载于:https://www.cnblogs.com/AdaByron/archive/2011/10/10/2205072.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值