nyoj19(排列组合next_permutation(s.begin(),s.end()))

本文介绍了一种使用C++实现的算法,该算法能够从n个数中选择m个数,并按字典序输出这些数的所有可能排列。通过使用next_permutation()函数并检查重复输出来实现这一目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目意思:

从n个数中选择m个数,按字典序输出其排列。

http://acm.nyist.net/JudgeOnline/problem.php?pid=19

例:

   输入:n=3。m=1; 输出:1 2 3

   输入:n=4。m=2; 输出:12 13 14 21 23 24 31 32 34 41 42 43


题目分析:

此题为全排列的前m个数。仅仅需对n个数调用全排列函数next_permutation()。去除反复的输出前m个就可以。


AC代码:

/**
 *改写的全排列,这里用字符串输入,方便推断是否反复输出
 */
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
using namespace std;
int n,m;
int main()
{
    int t;
    cin>>t;
    while(t--){
        cin>>n>>m;
        string s,s1;
        for(int i=1;i<=n;i++) s+=i+'0';
        s1=s.substr(0,m);
        cout<<s1<<endl;
        while(next_permutation(s.begin(),s.end())){
            if(s1!=s.substr(0,m)){//用来推断反复输出,否则会输出多次
                s1=s.substr(0,m);
                cout<<s1<<endl;
            }
        }
    }
    return 0;
}
       

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值