UVA10098Generating Fast

来源:互联网 发布:淘宝上蜂蜜是真的吗 编辑:程序博客网 时间:2024/04/29 19:11

UVA-10098

题意:给出一串字母,求它的全排列。
解题思路:一开始傻傻的直接排序完DFS求全排列WA了。看了题解发现是存在重复字母的,这样去dfs就会出现aabc 这种字符串的全排列中aabc会出现2次。所以要判断重复。要怎么判断呢,DFS做出来的全排列是按字典序来的,那么会重复的两个一定是相邻的,所只要和最后一次生成的答案比较就好了。

/*************************************************************************    > File Name: UVA-10098.cpp    > Author: Narsh    >     > Created Time: 2016年07月26日 星期二 15时48分31秒 ************************************************************************/#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>using namespace std;int t,n,l;char save[3700000][12],tmp[12];string c;bool pd[30];bool cmp(char a,char b) {    return a<b;}void dfs(int x) {    bool flag=true;    for (int i = 1; i <= n && flag; i++)        if (save[l-1][i] != tmp[i]) flag=false;    if ( flag && x!=1) return ;    if (x > n) {        if (!flag) {            for (int i = 1; i <= n; i++)                 save[l][i]=tmp[i];            l++;        }        return ;    }    for (int i = 1; i <= n; i++)        if (pd[i]) {            pd[i]=false;            tmp[x] = c[i];            dfs(x+1);            pd[i]=true;        }}int main() {    scanf("%d",&t);    while (t--) {        memset(tmp,0,sizeof(tmp));        memset(pd,true,sizeof(pd));        cin>>c;        n=c.length();        c=" "+c;        sort(&c[0]+1,&c[0]+1+n,cmp);        l=1;        dfs(1);        for (int i = 1; i < l; i++) {            for (int j = 1; j <= n; j++)                 printf("%c",save[i][j]);            printf("\n");        }        printf("\n");    }}
0 0
原创粉丝点击