计蒜客T1204 全排列

    科技2022-07-10  113

    对于全排列,看过题解知道有next_permutation这个函数,可以遍历生成给定序列的下一个较大的排列,直到整个序列为降序为止。prev_permutation函数与之相反,是生成给定序列的上一个较小的排列。

    使用方法:next_permutation(数组头地址,数组尾地址); 若下一个排列存在,则返回真,如果不存在则返回假。注意要包含头文件#include <algorithm>

    AC代码:

    #include<iostream> #include<algorithm> using namespace std; int main(){ string a; cin>>a; do{ cout<<a<<endl; }while(next_permutation(a.begin(),a.end())); return 0; }//感觉这题过的有点侥幸,并没有生成全排列

    此外,next_permutation(node, node+n, cmp)也可以对字符按照自定义的方式去排列。需要自定义比较函数cmp。 例如POJ 1256这题要求的字典序为'A'<'a'<'B'<'b'<...<'Z'<'z'.

    #include<iostream> #include<algorithm> #include<cstring> using namespace std; int cmp(char a,char b){ if(tolower(a)!=tolower(b))//tolower将大写字母转小写 return tolower(a)<tolower(b); else return a<b; } int main(){ string s; int n; cin>>n; while(n--){//输入n组数据 cin>>s; //如果不加自定义cmp,就会按照字典序来排,大写在前,小写在后 sort(s.begin(),s.end(),cmp); do{ cout<<s<<endl; }while(next_permutation(s.begin(),s.end(),cmp)); } return 0; }
    Processed: 0.013, SQL: 8