蓝桥杯算法提高 排列数

原题:


 

  算法提高 排列数  

时间限制:1.0s   内存限制:256.0MB

    

问题描述

  0、1、2三个数字的全排列有六种,按照字母序排列如下:
  012、021、102、120、201、210
  输入一个数n
  求0~9十个数的全排列中的第n个(第1个为0123456789)。

输入格式

  一行,包含一个整数n

输出格式

  一行,包含一组10个数字的全排列

样例输入

1

样例输出

0123456789

数据规模和约定

  0 < n <= 10!

思路:

 

        在这里简单介绍一下next_permutation函数,这是一个全排列函数,原理是直到当字符串按字典序为倒序为止。所以用在这里正好解决。代码如下:

 

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    string str = "0123456789";
    int n,m = 1;
    scanf("%d",&n);
    if(n == 1)
        printf("0123456789");
    else
        while (next_permutation(str.begin(), str.end()))
        {
            if(m == n - 1)
            {
                cout << str << endl;
                break;
            }
            m++;
        }
    return 0;
}

需要注意的是:

 

        因为while里面已经执行next-permutation()函数了,所以是开始就是第二个,所以如果输入1的话就直接输出。当然,也可以转化为do...while()形式:

 

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    string str = "0123456789";
    int n,m = 1;
    scanf("%d",&n);
    do{
        if(m++ == n)
        {
            cout<<str<<endl;
            break;
        }
    }while(next_permutation(str.begin(),str.end()));
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值