UVA 10098 用字典序思想生成所有排列组合

题目:

Generating permutation has always been an important problem in computer science. In this problem
you will have to generate the permutation of a given string in ascending order. Remember that your
algorithm must be efficient.
Input
The rst line of the input contains an integer n, which indicates how many strings to follow. The next
n lines contain n strings. Strings will only contain alpha numerals and never contain any space. The
maximum length of the string is 10.
Output
For each input string print all the permutations possible in ascending order. Not that the strings should
be treated, as case sensitive strings and no permutation should be repeated. A blank line should follow
each output set.
Sample Input
3
ab
abc
bca
Sample Output
ab
ba


abc
acb
bac
bca
cab
cba


abc
acb
bac
bca
cab
cba

题意:

输入字符串个数n,接下来依次输入n个字符串,要求按字典序从小到大输出每一个字符串的所有排列,不同字符串的全排列之间有一个空行。

分析:我在上一篇博客中写到了如何生成该字符串按字典序排列的下一个字符串--【https://www.cnblogs.com/cautx/p/11403927.html】

那么如何利用这个按字典序生成下一个排列的算法来生成全排列?

首先将该字符串按字典序从小到大排列:sort(s,s+len);

然后利用这个算法不断生成下一个排列并输出即可,只需要修改一下原算法的循环条件即可。

AC code1:

#include<bits/stdc++.h>
using namespace std;
char s[15];
int len;
int solve()
{
    int id=len-1;
    while(id>=0)
    {
        if(s[id-1]<s[id])    break;
        else id--;
    }
    if(id==0)    return 0;
    int mpre=id-1,mnow=id;
    for(int j=mnow+1;j<len;j++)
    {
        if(s[j]<=s[mpre])    continue;
        if(s[j]<s[mnow])    mnow=j;
    }
    swap(s[mnow],s[mpre]);
    sort(s+id,s+len);
    return 1;
}
int main()
{
    //freopen("input.txt","r",stdin);
    int n;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",s);
        len=strlen(s);
        sort(s,s+len);
        printf("%s\n",s);
        while(solve())    printf("%s\n",s);
        printf("\n");
    }
    return 0;
}
View Code

实际上,C++的STL的next_permutation(s,s+len)就是按照字典序来实现这个算法的。

AC code2:

#include<bits/stdc++.h>
using namespace std;
char s[15];
int main()
{
    //freopen("input.txt","r",stdin);
    int n;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",s);
        int len=strlen(s);
        sort(s,s+len);
        do{
            printf("%s\n",s);
        }while(next_permutation(s,s+len));
        printf("\n");
    }
    return 0;
}
View Code

 

posted on 2019-08-24 12:55  Caution_X  阅读(161)  评论(0编辑  收藏  举报

导航