您的位置:首页 > 其它

7 POJ 1256 Anagram

2015-04-29 21:28 260 查看
给一个字符串包含大小写字符,规定'A'<'a'<'B'<'b'<...<'Z'<'z',求该字符串的全排列。

用裸的dfs+map判重 写了一遍超时了,那种机智的dfs方法没有怎么看懂。。

最开始用的set+next_permutation,太年轻,也超时了。。。

运用一个next_permutation()函数即可,<algorithm>头文件

注意要先将字符串sort一遍,然后next_permutation()也要把比较函数cmp传进去,原来都不知道可以三个参数的。。

#include<cstdio>
#include<set>
#include<cstring>
#include<algorithm>
#include<string>
#include<iostream>
using namespace std;
char s[20];

bool cmp(char a,char b)
{
    if(a>='a'&&a<='z'&&b>='a'&&b<='z') return a<b;
    if(a>='A'&&a<='Z'&&b>='A'&&b<='Z') return a<b;
    if(abs(a-b)==32) return a<b;
    if(a>='A'&&a<='Z') a+=32;
    if(b>='A'&&b<='Z') b+=32;
    return a<b;
}
int main()
{
    int T,len;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s",s);
        len=strlen(s);
        sort(s,s+len,cmp);
        do
        {
            puts(s);
        }while(next_permutation(s,s+len,cmp));
    }
    return 0;
}


用裸的dfs+map判重 写了一遍超时了,那种机智的dfs方法没有怎么看懂。。

最开始用的set+next_permutation,太年轻,也超时了。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: