zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Oracle中merge into的使用
    ORACLE闪回操作 .
    Xmanager远程连接rel5 linux
    ORACLE EXPDP/IMPDP命令使用详细 .
    Oracle Hint
    Oracle中Union与Union All的区别
    关于文件不能访问,IIS提示MIME类型没有错误的解决方法
    当葱头碰上豆瓣酱时
    唯美之希望
    【出行贴士】全国旅游最佳时间
  • 原文地址:https://www.cnblogs.com/ACMans/p/4551162.html
Copyright © 2011-2022 走看看