标签:
1 /*
2 题意:手机划屏解锁,一笔连通所有数字,输出所有可能的路径;
3 DFS:全排列 + ok () 判断函数,去除一些不可能连通的点:)
4 */
5 #include <cstdio>
6 #include <iostream>
7 #include <algorithm>
8 #include <cstring>
9 #include <string>
10 #include <map>
11 #include <cmath>
12 #include <vector>
13 #include <set>
14 #include <queue>
15 using namespace std;
16
17 const int MAXN = 500000;
18 const int INF = 0x3f3f3f3f;
19 int a[11], ans[11];
20 int n, x;
21 int vis[11];
22 int res[MAXN][11];
23 int flag[10];
24
25 bool ok(void)
26 {
27 memset (flag, 0, sizeof (flag));
28
29 int i;
30 for (i=1; i<=n-1; i++) //小细节决定成败
31 {
32 flag[ans[i]] = 1;
33 if((ans[i] == 1 && ans[i+1] == 9 && flag[5] == 0)|| (ans[i] == 9 && ans[i+1] == 1 && flag[5] == 0) ||
34 (ans[i] == 1 && ans[i+1] == 3 && flag[2] == 0)|| (ans[i] == 3 && ans[i+1] == 1 && flag[2] == 0) ||
35 (ans[i] == 1 && ans[i+1] == 7 && flag[4] == 0)|| (ans[i] == 7 && ans[i+1] == 1 && flag[4] == 0) ||
36 (ans[i] == 2 && ans[i+1] == 8 && flag[5] == 0)|| (ans[i] == 8 && ans[i+1] == 2 && flag[5] == 0) ||
37 (ans[i] == 4 && ans[i+1] == 6 && flag[5] == 0)|| (ans[i] == 6 && ans[i+1] == 4 && flag[5] == 0) ||
38 (ans[i] == 3 && ans[i+1] == 9 && flag[6] == 0)|| (ans[i] == 9 && ans[i+1] == 3 && flag[6] == 0) ||
39 (ans[i] == 7 && ans[i+1] == 9 && flag[8] == 0)|| (ans[i] == 9 && ans[i+1] == 7 && flag[8] == 0) ||
40 (ans[i] == 3 && ans[i+1] == 7 && flag[5] == 0)|| (ans[i] == 7 && ans[i+1] == 3 && flag[5] == 0) )
41 return 0;
42
43 }
44 if(i == n)
45 return true;
46 }
47
48 void DFS(int cnt)
49 {
50 if (cnt == n + 1)
51 {
52 if (ok ())
53 {
54 x++;
55 for (int i=1; i<=n; i++)
56 {
57 res[x][i] = ans[i];
58 }
59 }
60
61 return ;
62 }
63
64 for (int i=1; i<=n; i++)
65 {
66 if (!vis[a[i]])
67 {
68 ans[cnt] = a[i];
69 vis[a[i]] = 1;
70 DFS (cnt + 1);
71 vis[a[i]] = 0;
72 }
73 }
74 }
75
76 int main(void) //ZOJ 3861 Valid Pattern Lock
77 {
78 //freopen ("B.in", "r", stdin);
79
80 int t;
81 scanf ("%d", &t);
82 while (t--)
83 {
84 //memset (res, -1, sizeof (res)); //这句话没写导致WA n次!!!
85 memset (vis, 0, sizeof (vis)); //注意初始化,上面的作用已在ok () Debug 出来了
86 scanf ("%d", &n);
87
88 for (int i=1; i<=n; ++i) scanf ("%d", &a[i]);
89 sort(a+1,a+n+1);
90 x = 0;
91 DFS (1);
92
93 printf ("%d\n", x);
94 for (int i=1; i<=x; ++i)
95 {
96 for (int j=1; j<=n; ++j)
97 {
98 printf ("%d%c", res[i][j], (j==n) ? ‘\n‘ : ‘ ‘);
99 }
100 }
101
102 }
103
104 return 0;
105 }
DFS+模拟 ZOJ 3861 Valid Pattern Lock
标签:
原文地址:http://www.cnblogs.com/Running-Time/p/4462969.html