DFS+模拟 ZOJ 3861 Valid Pattern Lock

题目传送门

 /*
题意:手机划屏解锁,一笔连通所有数字,输出所有可能的路径;
DFS:全排列 + ok () 判断函数,去除一些不可能连通的点:)
*/
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
#include <cmath>
#include <vector>
#include <set>
#include <queue>
using namespace std; const int MAXN = ;
const int INF = 0x3f3f3f3f;
int a[], ans[];
int n, x;
int vis[];
int res[MAXN][];
int flag[]; bool ok(void)
{
memset (flag, , sizeof (flag)); int i;
for (i=; i<=n-; i++) //小细节决定成败
{
flag[ans[i]] = ;
if((ans[i] == && ans[i+] == && flag[] == )|| (ans[i] == && ans[i+] == && flag[] == ) ||
(ans[i] == && ans[i+] == && flag[] == )|| (ans[i] == && ans[i+] == && flag[] == ) ||
(ans[i] == && ans[i+] == && flag[] == )|| (ans[i] == && ans[i+] == && flag[] == ) ||
(ans[i] == && ans[i+] == && flag[] == )|| (ans[i] == && ans[i+] == && flag[] == ) ||
(ans[i] == && ans[i+] == && flag[] == )|| (ans[i] == && ans[i+] == && flag[] == ) ||
(ans[i] == && ans[i+] == && flag[] == )|| (ans[i] == && ans[i+] == && flag[] == ) ||
(ans[i] == && ans[i+] == && flag[] == )|| (ans[i] == && ans[i+] == && flag[] == ) ||
(ans[i] == && ans[i+] == && flag[] == )|| (ans[i] == && ans[i+] == && flag[] == ) )
return ; }
if(i == n)
return true;
} void DFS(int cnt)
{
if (cnt == n + )
{
if (ok ())
{
x++;
for (int i=; i<=n; i++)
{
res[x][i] = ans[i];
}
} return ;
} for (int i=; i<=n; i++)
{
if (!vis[a[i]])
{
ans[cnt] = a[i];
vis[a[i]] = ;
DFS (cnt + );
vis[a[i]] = ;
}
}
} int main(void) //ZOJ 3861 Valid Pattern Lock
{
//freopen ("B.in", "r", stdin); int t;
scanf ("%d", &t);
while (t--)
{
//memset (res, -1, sizeof (res)); //这句话没写导致WA n次!!!
memset (vis, , sizeof (vis)); //注意初始化,上面的作用已在ok () Debug 出来了
scanf ("%d", &n); for (int i=; i<=n; ++i) scanf ("%d", &a[i]);
sort(a+,a+n+);
x = ;
DFS (); printf ("%d\n", x);
for (int i=; i<=x; ++i)
{
for (int j=; j<=n; ++j)
{
printf ("%d%c", res[i][j], (j==n) ? '\n' : ' ');
}
} } return ;
}
上一篇:牛客~~扫雷~~~DFS+模拟


下一篇:UVALive 5880 Vigenère Cipher Encryption (模拟)