huangriq

导航

poj 1256(搜索)

B - B
Time Limit:1000MS Memory Limit:10000KB 64bit IO Format:%I64d & %I64u

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.

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

3
aAb
abc
acba

Sample Output

Aab
Aba
aAb
abA
bAa
baA
abc
acb
bac
bca
cab
cba
aabc
aacb
abac
abca
acab
acba
baac
baca
bcaa
caab
caba
cbaa

Hint

An upper case letter goes before the corresponding lower case letter.
So the right order of letters is 'A'<'a'<'B'<'b'<...<'Z'<'z'.

 

 

思路:DFS求全排列,当然需要剪枝,把题目给出的字符串案给出规则排序,DFS全排列的时候,当前后个字母相同且前面字母没选的时候,后面的字母可直接跳过不选。

View Code
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 char str[55],sstr[55];
 7 int b[55],a[55],pos[550];
 8 int top;
 9 int comp(const void *a,const void *b)
10 {
11     return *(int *)a>*(int *)b?1:-1;
12 }
13 void dfs(int deep)
14 {
15     if(deep==top)
16     {
17         sstr[deep]='\0';
18         puts(sstr);
19     }
20     for(int i=0;i<top;i++)
21     {
22         if(i>0&&a[i]==a[i-1]&&!b[i-1])continue;//重要剪枝
23         if(!b[i])
24         {
25             if(a[i]%2==0)sstr[deep]=a[i]/2+'A';
26             else sstr[deep]=a[i]/2+'a';
27             b[i]=1;
28             dfs(deep+1);
29             b[i]=0;
30         }
31     }
32 }
33 int main()
34 {
35     int ca;
36     for(int i=0;i<26;i++)
37     {
38         pos['a'+i]=i*2+1;
39         pos['A'+i]=i*2;
40     }
41     scanf("%d",&ca);
42     getchar();
43     while(ca--)
44     {
45         gets(str);
46         top=0;
47         for(int i=0;str[i];i++)
48         {
49             a[top++]=pos[str[i]];
50         }
51         qsort(a,top,sizeof(int),comp);
52         dfs(0);
53     }
54     return 0;
55 }

 

posted on 2012-05-12 22:38  huangriq  阅读(243)  评论(0编辑  收藏  举报