POJ 1256.Anagram

2015-06-04

问题简述:

  输出一串字符的全排列,顺序不同于一般的字母序,而是 A<a<B<b......<Z<z。所以应该重写一个比较函数。

  原题链接:http://poj.org/problem?id=1256

解题思路:

  两种方法:

  方法一:简单的深搜 DFS 搜索所有的可能,但是要注意几个连续相同的字符算作一种情况。

  方法二:使用 STL 的 next_permutation 函数可以很方便的生成全排列。

      关于 next_permutation 函数,可以参考:姜南(Slyar)的文章(点击直接跳转) 感谢原作者!

 

DFS源代码:

 1  /*
 2 OJ: POJ
 3 ID: 3013216109
 4 TASK: 1256.Anagram
 5 LANG: C++
 6 NOTE: DFS
 7 */
 8 #include <cstdio>
 9 #include <string>
10 #include <cstring>
11 #include <algorithm>
12 using namespace std;
13 
14 int n;
15 char str[13],ans[13];
16 int visited[13];
17 
18 bool cmp(char a,char b) {
19     if(tolower(a)==tolower(b))
20         return a<b;
21     else
22         return tolower(a)<tolower(b);
23 }
24 
25 void dfs(int t) {
26     if(t==strlen(str)) {
27         for(int i=0;i<t;i++)
28             printf("%c",ans[i]);
29         printf("\n");
30         return;
31     }
32     for(int i=0;i<strlen(str);i++) {
33         if(!visited[i]) {
34             ans[t]=str[i];
35             visited[i]=1;
36             dfs(t+1);
37             visited[i]=0;
38             while(i+1<strlen(str)&&str[i]==str[i+1]) i++;
39         }
40     }
41 }
42 
43 int main()
44 {
45     scanf("%d",&n);
46     getchar();
47     while(n--) {
48         memset(visited,0,sizeof(visited));
49         gets(str);
50         sort(str,str+strlen(str),cmp);
51         dfs(0);
52     }
53     return 0;
54 }

 

STL源代码:

 

 1  /*
 2 OJ: POJ
 3 ID: 3013216109
 4 TASK: 1256.Anagram
 5 LANG: C++
 6 NOTE: NEXT_PERMUTATION
 7 */
 8 #include <cstdio>
 9 #include <string>
10 #include <cstring>
11 #include <algorithm>
12 using namespace std;
13 
14 int n;
15 char str[13];
16 
17 bool cmp(char a,char b) {
18     if(tolower(a)==tolower(b))
19         return a<b;
20     else
21         return tolower(a)<tolower(b);
22 }
23 
24 
25 int main()
26 {
27     scanf("%d",&n);
28     getchar();
29     while(n--) {
30         gets(str);
31         sort(str,str+strlen(str),cmp);
32         do {
33             puts(str);
34         } while(next_permutation(str,str+strlen(str),cmp));
35     }
36     return 0;
37 }

 

转载于:https://www.cnblogs.com/ACMans/p/4551162.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值