求全排列 next_permutation(begin,end)

//求全排列  next_permutation(begin,end)
/*
next_permutation(start,end),和prev_permutation(start,end)。这两个函数作用是一样的,区别就在于前者求的是当前排列的下一个排列,后一个求的是当前排列的上一个排列。至于这里的“前一个”和“后一个”,我们可以把它理解为序列的字典序的前后,严格来讲,就是对于当前序列pn,他的下一个序列pn+1满足:不存在另外的序列pm,使pn<pm<pn+1.
*/
//数组的方式
int a[3];
do{
    printf("%d %d %d\n",a[0],a[1],a[2]);
}while(next_permutation(a,a+3));
//输出全排列//要从最小的开始
    //vector
    vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(4);
    do{
        copy (vec.begin(), vec.end(), ostream_iterator<int>{cout, " "});
        cout << endl;
    }while(next_permutation(vec.begin(), vec.end()));
    //string
    vector<string> vec;
    vec.push_back("one");
    vec.push_back("two");
    vec.push_back("three");
    vec.push_back("four");
    while(next_permutation(vec.begin(),vec.end()))
    do{
        copy(vec.begin(),vec.end(),ostream_iterator<string>{cout," "});
        cout<<endl;
    }while(next_permutation(vec.begin(),vec.end()));
    //string的优化方式   同时还可以是从某种开始的全排列的生成方式
    vector<string> vec;

    vec.push_back("one");
    vec.push_back("two");
    vec.push_back("three");
    vec.push_back("four");

    vector<string> vec_copy = vec; // Copy the original
    do {
        copy(vec.begin(),vec.end(),ostream_iterator<string>{cout, " "});
        cout << endl;
        next_permutation(vec.begin(),vec.end());
    }while(vec != vec_copy); // Continue until back to the original

    
//输出最小的排列方式
vector<int> vec;
vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(4);
    for (vector<int>::iterator iter = vec.begin(); iter != vec.end()-1 ;++iter)
        iter_swap(iter, min_element(iter,vec.end()));
    for (vector<int>::iterator iter = vec.begin(); iter != vec.end() ;++iter)
        cout<<*iter<<endl;

//next_permutation(a,a+3,cmp)自定义方式排列
 'A'<'a'<'B'<'b'<...<'Z'<'z'.
bool com(char a,char b){
    if(tolower(a)!=tolower(b))return tolower(a)<tolower(b);
    else return a<b;
}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int n;
    char ch[14];
    cin>>n;
    while(n--){
        cin>>ch;
        sort(ch,ch+strlen(ch),com);
        do{
            cout<<ch<<endl;
        }while(next_permutation(ch,ch+strlen(ch),com));
    }
     return 0;
}


//求某个字符串的全排列在一个字符串中一共出现多少次
//dp数组存的是从这个位置开始(包括这个位置)数组中的字符的最近的位置
# include <bits/stdc++.h>
using namespace std;

const int MAXN=3100;
char s[]="abcdefghi";
char s1[MAXN];
int dp[MAXN][10];
int id[10];
int main()
{
    scanf("%s",s1+1);
    int ans=0;
    for(int i=strlen(s1+1);i>=0;i--){
        for(int j=0;j<9;j++){
            dp[i][j]=id[j];
        }
        if(i!=0) id[s1[i]-'a']=i;
    }
    
    do{
        int p=0;
        for(int i=0;i<9;i++){
            p=dp[p][s[i]-'a'];
            if(p==0) break;
        }
        if(p!=0) ans++;
    }while(next_permutation(s,s+9));
    
    printf("%d\n",ans);
    return 0;
}

posted @ 2022-02-26 23:23  fengzlj  阅读(43)  评论(0)    收藏  举报