ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2019-08-24 13:02:18  阅读:253  来源: 互联网

标签:int 10098 len 排列组合 字符串 UVA 字典 strings permutation


题目:

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

 

标签:int,10098,len,排列组合,字符串,UVA,字典,strings,permutation
来源: https://www.cnblogs.com/cautx/p/11404286.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有