深度优先搜索 之 CODE[VS] 1294 全排列

/*
注意:
	输入输出采用scanf、printf,防止TLE。
 
两种实现方法:
	(1)void Solve(int numPos, int isUsed); // dfs
	(2)void SolveWithSTL();
	       C++ STL 自带函数,可生成全排列 next_permutation( ),
	       详细文档:http://www.cplusplus.com/reference/algorithm/next_permutation/?kw=next_permutation
*/
 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <cstdio>
 4 #include <cstddef>
 5 #include <iterator>
 6 #include <algorithm>
 7 #include <string>
 8 #include <locale>
 9 #include <cmath>
10 #include <vector>
11 #include <cstring>
12 #include <map>
13 #include <utility>
14 #include <queue>
15 #include <stack>
16 #include <set>
17 using namespace std;
18 const int INF = -0x3f3f3f3f;
19 const int MaxN = 55;
20 const int modPrime = 3046721;
21 
22 int n;
23 int arr[15];
24 
25 void Solve(int numPos, int isUsed)
26 {
27     if (numPos == (n + 1))
28     {
29         for (int i = 1; i <= n; ++i)
30         {
31             printf("%d ", arr[i]);
32         }
33         printf("\n");
34     }
35     for (int i = 1; i <= n; ++i)
36     {
37         if (!(isUsed&(1 << i)))
38         {
39             arr[numPos] = i;
40             Solve(numPos + 1, isUsed|(1 << i));
41         }
42     }
43 }
44 
45 
46 void SolveWithSTL()
47 {
48     for (int i = 1; i <= n; ++i)
49     {
50         arr[i] = i;
51     }
52     do
53     {
54         for (int i = 1; i <= n; ++i)
55         {
56             printf("%d ", arr[i]);
57         }
58         printf("\n");
59     } while (next_permutation(arr + 1, arr + n + 1));
60 }
61 
62 int main()
63 {
64 #ifdef HOME
65     freopen("in", "r", stdin);
66     //freopen("out", "w", stdout);
67 #endif
68 
69     scanf("%d", &n);
70     //Solve(1, 0);
71     SolveWithSTL();
72 
73 #ifdef HOME
74     cerr << "Time elapsed: " << clock() / CLOCKS_PER_SEC << " ms" << endl;
75     _CrtDumpMemoryLeaks();
76 #endif
77     return 0;
78 }

 

 
posted @ 2015-12-04 15:13  JmingS  阅读(198)  评论(0编辑  收藏  举报