poj 1256 深搜全排列 Anagram

来源:互联网 发布:如何修改电脑网络通道 编辑:程序博客网 时间:2024/06/07 00:42

Anagram

Time Limit 4000ms

Memory Limit 65536K

description

You are to write a program that has to generate all possible words from a given set of letters. Example: Given the word "abc", your program should - by exploring all different combination of the three letters - output the words "abc", "acb", "bac", "bca", "cab" and "cba". In the word taken from the input file, some letters may appear more than once. For a given word, your program should not produce the same word more than once, and the words should be output in alphabetically ascending order.An upper case letter goes before the corresponding lower case letter. So the right order of letters is 'A'<'a'<'B'<'b'<...<'Z'<'z'. 

input

The input consists of several words. The first line contains a number giving the number of words to follow. Each following line contains one word. A word consists of uppercase or lowercase letters from A to Z. Uppercase and lowercase letters are to be considered different. The length of each word is less than 13. 

output

For each word in the input, the output should contain all different words that can be generated with the letters of the given word. The words generated from the same input word should be output in alphabetically ascending order. An upper case letter goes before the corresponding lower case letter. 

sample_input

3aAbabcacba

sample_output

AabAbaaAbabAbAabaAabcacbbacbcacabcbaaabcaacbabacabcaacabacbabaacbacabcaacaabcabacbaa



#include <iostream>#include <math.h>#include <stdlib.h>#include <string.h>#include <stdio.h>#include <algorithm>using namespace std;char str[15],a[15];int vis[15];int len;bool cmp(char a,char b){    double c1=a,c2=b;    if(a>='A'&&a<='Z')        c1+=31.5;    if(b>='A'&&b<='Z')        c2+=31.5;    return c1<c2;}void dfs(int x){    int i;    if(x==len)    {        for(i=0;i<len;i++)            printf("%c",a[i]);        cout<<endl;    }    else    {        for(i=0;i<len;i++)        {            if(!vis[i])            {                a[x]=str[i];                vis[i]=1;                dfs(x+1);                vis[i]=0;                while(i+1<len&&str[i+1]==str[i]) //不能出现重复的                    i++;            }        }    }}int main(){    int t;    while(cin>>t)    {        while(t--)        {            memset(vis,0,sizeof(vis));            scanf("%s",str);            len=strlen(str);            sort(str,str+len,cmp);            dfs(0);        }    }}


原创粉丝点击