POJ 1256.Anagram

描述

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. 

输入

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.

输出

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.

样例输入

3
aAb
abc
acba

样例输出

Aab
Aba
aAb
abA
bAa
baA
abc
acb
bac
bca
cab
cba
aabc
aacb
abac
abca
acab
acba
baac
baca
bcaa
caab
caba
cbaa
注意这道题不是按照字典序输出,而是按照题目给定的顺序输出。大写字母排在相应的小写字母前面。


这道题的思路参考: 吴永辉、王建德 算法设计编程实验 P158

这种思路让我眼前一亮的是: 它在每一层会申请一个新的数组用来标记这一层a - Z 中的字母被放置过当前位置上否。
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
#define init() ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
using namespace std;
int has[15];
char s[15],p[15];
int len;

bool cmp(char a,char b)   // 根据题意写排序规则
{
    char c,d;
    if (a <= 'Z' && a >= 'A')
    c = a - 'A' + 'a';
    else c = a;
    if (b <= 'Z' && b >= 'A')
    d = b-'A'+'a';
    else d = b;
    if (c == d)
    {
        return a < b;
    }
    else return c < d;
}

void dfs(int idx){
    
    if (idx == len){
        printf("%s\n",p);
        return;
    }
    int visit[58];
    memset(visit,0,sizeof(visit));
    for (int i = 0 ; i < len; ++i){
        if (!visit[s[i] - 'A'] && !has[i]){
            has[i] = 1;
            visit[s[i] - 'A'] = 1;
            p[idx] = s[i];
            dfs(idx + 1);
            has[i] = 0;
        }
    }
}


int main(){
    int n;
    cin>>n;
    for (int i = 0 ; i < n; ++i){
            memset(p,0,sizeof(p));
            cin>>s;
            len = strlen(s);
            sort(s,s+len,cmp);
            dfs(0);
            
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值