南阳19--擅长排列的小明(Dfs)

 

时间限制:1000 ms  |  内存限制:65535 KB
难度:4
 
描述
小明十分聪明,而且十分擅长排列计算。比如给小明一个数字5,他能立刻给出1-5按字典序的全排列,如果你想为难他,在这5个数字中选出几个数字让他继续全排列,那么你就错了,他同样的很擅长。现在需要你写一个程序来验证擅长排列的小明到底对不对。
 
输入
第一行输入整数N(1<N<10)表示多少组测试数据,
每组测试数据第一行两个整数 n m (1<n<9,0<m<=n)
输出
在1-n中选取m个字符进行全排列,按字典序全部输出,每种排列占一行,每组数据间不需分界。如样例
样例输入
2
3 1
4 2
样例输出
1
2
3
12
13
14
21
23
24
31
32
34
41
42
43
来源
[hzyqazasdf]原创
上传者
hzyqazasdf
 1  #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 using namespace std;
 5 int dis[15], vis[15];
 6 int n, m;
 7 void Dfs(int a)
 8 {
 9     if(a == m)
10     {
11         for(int i = 0; i < m; i++)
12             printf("%d", dis[i]);
13         printf("
");
14         return; 
15     } 
16     else
17     {
18         for(int j = 1; j <= n; j++)
19         {
20             if(vis[j])
21                 continue;
22             vis[j] = 1;
23             dis[a] = j;
24             Dfs(a + 1);
25             vis[j] = 0;
26         } 
27     }
28 }
29 int main()
30 {
31     int t;
32     scanf("%d", &t);
33     while(t--)
34     {
35         memset(vis, 0, sizeof(vis)); 
36         scanf("%d %d", &n, &m);
37         Dfs(0);
38     }
39     return 0;
40 }  

 STL-- (next_permutation(a, a + n)) 包含在头文件 algorithm中 。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <algorithm>
 5 using namespace std;
 6 int main()
 7 {
 8     int t, list[10];
 9     scanf("%d", &t);
10     while(t--)
11     {
12         int n, m;
13         scanf("%d %d", &n, &m);
14         for(int i = 0; i < n; i++)
15             list[i] = i + 1;
16         int pre = 0;
17         do{
18             if(list[m-1] != pre){
19                 for(int i = 0; i < m; i++)
20                     cout << list[i];
21                 cout << endl;
22                 pre = list[m-1];
23             }
24         }while(next_permutation(list, list + n));
25     }
26     return 0;
27 }
原文地址:https://www.cnblogs.com/soTired/p/4722825.html