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

题目意思:

从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;
}
       

原文地址:https://www.cnblogs.com/yfceshi/p/7084116.html