next_permutation ( ) : HDU-1027 Ignatius and the Princess II 和 HDU-1716 排列2

HDU-1027 Ignatius and the Princess II

HDU-1027 Ignatius and the Princess II

题意

给出 n,m,求出从 1 - n 的第 m 小的序列。

thinking

利用 STL 里的求下一个排列组合的函数 next_permutation()。
next_permutation()求出一个序列字典序的下一个,排序范围是 [ first, last ).

code

#include <iostream>
#include <algorithm>
using namespace std;
int a[10009];
int main(){
    int n,m;
    while (cin >> n >> m){
        for (int i = 1; i <= n; ++i) {
            a[i] = i;
        }
        int count=1;
        while (count<m){
            next_permutation(a+1,a+1+n);
            count++;
        }
        for (int j = 1; j <= n; ++j) {
            cout << a[j];
            if (j!=n) cout << ' ';
        }
        cout << endl;
    }
}

HDU-1716 排列2

HDU-1716 排列2

题意

给出四个数
按照从小到大排序
千位数一样的为一行
样例之间空一行
最后一个样例之后不空

think

一开始没有很好的理解 next_permutation()以至于出现重复的,处理了一番,白饶了一圈。
next_permutation()如果没有下一个排列将会返回 false,所以可以直接判断有无排列过,就不会存在重复的了。
用 flag 帮助输出空格的情况。
输入数字后在判断是否为最后一个数,来判断是否要输出空格。

code

#include <iostream>
#include <algorithm>

using namespace std;
int a[10009];
int main(){
    cin >> a[0] >> a[1] >> a[2] >> a[3];
    while ((a[0]||a[1]||a[2]||a[3])){
        int th = a[0];
        int flag=0;
        do{
            if (a[0]==th&&a[0]){
                if (flag) cout << ' ';
                printf("%d%d%d%d",a[0],a[1],a[2],a[3]);
                flag=1;
            } else if(a[0]){
                if (th){
                    th = a[0];
                    printf("\n%d%d%d%d",a[0],a[1],a[2],a[3]);
                } else{
                    th = a[0];
                    printf("%d%d%d%d",a[0],a[1],a[2],a[3]);
                    flag=1;
                }
            }
        }while(next_permutation(a, a + 4));
        cout <<'\n';
        cin >> a[0] >> a[1] >> a[2] >> a[3];
        if ((a[0]||a[1]||a[2]||a[3])) cout<<"\n";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值