[ An Ac a Day ^_^ ] hdu 2553 N皇后问题 搜索

时间:2023-03-08 18:55:18

曾经想过一天一AC 坚持下来的确不容易额 (我是没坚持下来 尽量以后坚持……

经典的N皇后问题 搜索的入门问题 学了这么久竟然一直没敲过 今天敲一下……

这道题也不是很简单额 纯暴力就超时了 要打一下表……

而且有一个小的优化

每次判断是否合理不用铺满图再判断

只需要判断当前放皇后的位置的上方 左上和右上有没有皇后就可以了

自己想也不好想-_-||

 #include<stdio.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<string>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<list>
#define M(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=1e1+;
int dx[]= {,,,-,,-,,-};
int dy[]= {,-,,,-,,,-};
//---------------------------------------ヽ(^。^)丿
int cnt,n,ans[maxn];
int _map[maxn];
void dfs(int x)
{
if(x>n)
{//只要能搜到这一步一定符合条件了
cnt++;
return ;
}
for(int i=; i<=n; i++)
{
_map[x]=i; //放置皇后
bool ok=true;
for(int j=x-;j>=;j--)
if(_map[j]==i|| //正上方
_map[j]==i-x+j|| //左上方
_map[j]==i+x-j) //右上方
ok=false;
if(ok) dfs(x+); //符合条件继续搜索
}
return ;
}
int main()
{
M(ans,-);
while(~scanf("%d",&n)&&n)
{
if(ans[n]!=-)
printf("%d\n",ans[n]);
else
{
M(_map,-);
cnt=;
dfs();
ans[n]=cnt; //打表
printf("%d\n",cnt);
}
}
return ;
}
/* 1
8
5
0 */