SCAU 算法课的题

8594 有重复元素的排列问题(优先做)

时间限制:1000MS  内存限制:1000K
提交次数:1610 通过次数:656

题型: 编程题   语言: G++;GCC;VC

 

Description

设集合R={r1,r2,...,rn}是要进行排列的n个元素,其中r1,r2,...,rn可能相同。
试着设计一个算法,列出R的所有不同排列。
即,给定n以及待排的n个可能重复的元素。计算输出n个元素的所有不同排列。




输入格式

第1行是元素个数n,1<=n<=15。接下来的1行是待排列的n个元素,元素中间不要加空格。



输出格式

程序运行结束时,将计算输出n个元素的所有不同排列。最后1行中的数是排列总数。

(说明:
此题,所有计算出的排列原本是无所谓顺序的。但为了容易评判,输出结果必须唯一!
现做约定:所有排列的输出顺序如课本例2-4的程序段的输出顺序,区别仅是这道题是含
重复元素。)



 

输入样例

4
aacc



 

输出样例

aacc
acac
acca
caac
caca
ccaa
6

构造函数F(be, en)表示要对这个区间进行全排列
那么F(be, en)的结果相当于第一位是谁谁谁的 + F(be + 1, en)的结果
如果可以重复,那么第一位没有限定
但是这题有重复,那么和第一位换过的元素就不能再次换
就相当于第一位只能出现a、b、c、d、e.....只能一次

 

 

#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
using namespace std;
#define IOS ios::sync_with_stdio(false)
using namespace std;
#define inf (0x3f3f3f3f)
typedef long long int LL;
char str[222];
int ans;
bool is[22][222];
void fun(int be, int en) {
    if (be == en) {
        ans++;
        printf("%s
", str + 1);
        return;
    }
    is[be][str[be]] = true;
    fun(be + 1, en);
    for (int i = be + 1; i <= en; ++i) {
        if (is[be][str[i]]) continue;
        is[be][str[i]] = true;
        swap(str[be], str[i]);
        fun(be + 1, en);
        swap(str[be], str[i]);
    }
    memset(is[be], false, sizeof is[be]);
}
void work() {
    int lenstr;
    scanf("%d", &lenstr);
    scanf("%s", str + 1);
    fun(1, lenstr);
    printf("%d
", ans);
}

int main() {
#ifdef local
    freopen("data.txt", "r", stdin);
//    freopen("data.txt", "w", stdout);
#endif
    work();
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/liuweimingcprogram/p/7764529.html