【HDU 2553】 N皇后问题

来源:互联网 发布:js setcookie 作用域 编辑:程序博客网 时间:2024/05/21 15:45

在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上。 
你的任务是,对于给定的N,求出有多少种合法的放置方法。 

Input
共有若干行,每行一个正整数N≤10,表示棋盘和皇后的数量;如果N=0,表示结束。
Output
共有若干行,每行一个正整数,表示对应输入行的皇后的不同放置数量。
Sample Input
1850
Sample Output
19210




N皇后问题比较经典了,在紫书上也有讲,但是交上去总是TLE,后来发现是记录上出了问题,在计算答案之前先循环计算1-10的答案并记录在一个数组中,输入n之后直接调用数组答案输出即可

#include<iostream>#include<algorithm>#include<cstring>#include<cmath>#include<cstdio>#include<queue>using namespace std;int tot, n, c[11];void search_(int cur, int k){    if(cur == k)        tot++;    else{        for(int i = 0; i < k; i++){            int ok  = 1;            c[cur] = i;            for(int j = 0; j < cur; j++)            {                if(c[cur] == c[j] || cur - c[cur] == j - c[j] || cur + c[cur] == j + c[j])                {                    ok = 0;                    break;                }            }            if(ok)                search_(cur + 1, k);        }    }}int main(){    int oldAns[11];    memset(oldAns, 0, sizeof(oldAns));    for(int i = 0; i <= 10; i++)    {        tot = 0;        search_(0, i);        oldAns[i] = tot;    }    while(scanf("%d", &n) != EOF && n)    {        cout<<oldAns[n]<<endl;    }    return 0;}