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

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



 

提示

课本上有“递归”实现无重复元素全排列的源程序。
稍加修改即可满足此题要求。

在递归产生全排列的那段程序开始之前,
加一个判断:判断第i个元素是否在list[k,i-1]中出现过。
PermExcludeSame(char list[], int k, int m)
{
  ......
  for (int i=k; i<=m; i++)
  {
    if (Findsame(list,k,i))//判断第i个元素是否在list[k,i-1]中出现过
       continue;
    Swap (list[k], list[i]);
    PermExcludeSame(list, k+1, m);
    Swap (list[k], list[i]);
  }
}


我的代码实现

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #define N 100005
 4 
 5 
 6 int count=0;
 7 
 8 //int cmp(const void *a,const void *b){
 9 //    return *(char *)a-*(char *)b;
10 //}
11 
12 
13 void swap(char *a,char *b){
14         char temp;
15         temp=*a;
16         *a=*b;
17         *b=temp;
18 }
19 
20 
21 bool Findsame(char list[],int k,int m){//判断第m个元素是否在list[k,m-1]中出现过
22     for(int i=k;i<m;i++){
23         if(list[i]==list[m])return true;
24     }
25     return false;
26 }
27 
28 void Perm(char list[],int k,int m){
29     if(k==m){
30         for(int i=0;i<=m;i++){
31             printf("%c",list[i]);
32         }
33         printf("
");
34         count++;
35     }
36     else{
37         for(int i=k;i<=m;i++){
38             if(Findsame(list,k,m))continue; 
39             swap(&list[k],&list[i]);
40             Perm(list,k+1,m);
41             swap(&list[k],&list[i]);
42         }
43     }
44  
45 } 
46 
47 
48 
49 int main(){
50     int n;
51     scanf("%d",&n);
52     char str[N];
53     scanf("%s",str);
54 //    qsort(str,n,sizeof(str[0]),cmp);
55 //    for(int i=0;i<n;i++){
56     Perm(str,0,n-1);
57     printf("%d",count);
58 //    }
59     return 0;
60 }


 
原文地址:https://www.cnblogs.com/double891/p/7855948.html