题目19:擅长排列的小明

来源:互联网 发布:唐嫣丑 知乎 编辑:程序博客网 时间:2024/05/20 14:28

题目链接

http://acm.nyist.net/JudgeOnline/problem.php?pid=19

描述

小明十分聪明,而且十分擅长排列计算。比如给小明一个数字5,他能立刻给出1-5按字典序的全排列,如果你想为难他,在这5个数字中选出几个数字让他继续全排列,那么你就错了,他同样的很擅长。现在需要你写一个程序来验证擅长排列的小明到底对不对。

输入

第一行输入整数N表示多少组测试数据,
每组测试数据第一行两个整数 n m

输出

在1-n中选取m个字符进行全排列,按字典序全部输出,每种排列占一行,每组数据间不需分界。如样例

样例输入

2
3 1
4 2

样例输出

1
2
3
12
13
14
21
23
24
31
32
34
41
42
43

算法思想

这个题目如果想投机取巧的话可以使用C++ STL中的全排列函数。自己也可以实现全排列函数,主要使用到组合数学的一些知识。查看了最优代码,主要使用的是深度搜索、递归。因为递归不具有重现性,所以在此最优代码使用了两个数组来保存一些信息。其中used[10]数组主要是用于判断排列中是否有重复元素,使得能跳跃重复元素。ans[11]数组用于记录排列结果。这样使用深度搜索就能完成排列过程。

最优代码

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <algorithm>using namespace std;int n, m, used[10];char ans[11];void dfs(int x, int num){    if (num == m - 1)    {        ans[m] = '\0';        printf("%s\n", ans);        return;    }    int i;    for (i = 1; i <= n; i++)    {        if (!used[i])        {            used[i] = 1;            ans[num + 1] = i + '0';            dfs(i, num + 1);            used[i] = 0;        }    }}int main(){    int i, t;    scanf("%d", &t);    while (t--)    {        scanf("%d%d", &n, &m);        for (i = 1; i <= n; i++)        {            memset(used, 0, sizeof(used));            used[i] = 1;            ans[0] = i + '0';            dfs(i, 0);        }    }    return 0;}

算法复杂度

由于需要递归,故该算法的时间复杂度为O(n^m),空间复杂度为O(n)。

全排列算法

算法思想

可以使用字典序法算法和序数法算法,我在这写的是字典序法。其算法思想如下图所示。
这里写图片描述

全排序源代码

#include <iostream>#include <algorithm>#include <cstring>using namespace std;int less_cmp(const void *x, const void *y){    return (int *)x - (int *)y;}void arrangement(int a[], int num){    int pos;    for (int i = num - 1; i >= 1; i--)    {        //找出比右邻小的第一个元素        if (a[i] > a[i - 1])        {            pos = i - 1;    //记录该位置            for (int j = num - 1; j >= 0; j--)  //从右往左扫描,找出比a[pos]大的第一个元素,将其与a[pos]互换            {                if (a[j] > a[pos])                {                    swap(a[j], a[pos]);                    break;                }            }            //将a[pos]到a[num]部分顺序逆转            qsort(a + pos, num - pos + 1, sizeof(a[0]), less_cmp);            i = num - 1;            for (int j = 0; j < num; j++)            {                cout << a[j];            }            cout << endl;        }    }}int main(){    int  m, *a;    cout << "请输入要排序元素个数m以及各个元素" << endl;    cin >> m;    a = new int[m];    for (int i = 0; i < m; i++)    {        cin >> a[i];    }    cout << "全排序结果:" << endl;    arrangement(a,m);    return 0;}
原创粉丝点击