Time Limit: 1000MS | Memory Limit: 131072K | |||
Total Submissions: 2897 | Accepted: 1067 | Special Judge |
Description
The eight queens puzzle is the problem of putting eight chess queens on an 8 × 8 chessboard such that none of them is able to capture any other. The puzzle has been generalized to arbitraryn ×n boards. Given n, you are to find a solution to then queens puzzle.

Input
The input contains multiple test cases. Each test case consists of a single integern between 8 and 300 (inclusive). A zero indicates the end of input.
Output
For each test case, output your solution on one line. The solution is a permutation of {1, 2, …,n}. The number in theith place means the ith-column queen in placed in the row with that number.
Sample Input
8 0
Sample Output
5 3 1 6 8 2 4 7
题意:在N*N的上 摆下N个皇后 使得所有的皇后都不会被其他皇后攻击;
皇后 可以 攻击到 同行 列 ,斜线;
思路:不知道怎么构造,只会DFS 回溯
但是N的范围到了300,太大了 DFS效率太低。
网上看到牛人想出来的 构造公式 好强大了 ORZ、
/*
n皇后问题构造法:
一、当n mod 6 != 2 且 n mod 6 != 3时,有一个解为:
2,4,6,8,...,n,1,3,5,7,...,n-1 (n为偶数)
2,4,6,8,...,n-1,1,3,5,7,...,n (n为奇数)
(上面序列第i个数为ai,表示在第i行ai列放一个皇后;...省略的序列中,相邻两数以2递增。下同)
二、当n mod 6 == 2 或 n mod 6 == 3时,
(当n为偶数,k=n/2;当n为奇数,k=(n-1)/2)
k,k+2,k+4,...,n,2,4,...,k-2,k+3,k+5,...,n-1,1,3,5,...,k+1 (k为偶数,n为偶数)
k,k+2,k+4,...,n-1,2,4,...,k-2,k+3,k+5,...,n-2,1,3,5,...,k+1,n (k为偶数,n为奇数)
k,k+2,k+4,...,n-1,1,3,5,...,k-2,k+3,...,n,2,4,...,k+1 (k为奇数,n为偶数)
k,k+2,k+4,...,n-2,1,3,5,...,k-2,k+3,...,n-1,2,4,...,k+1,n (k为奇数,n为奇数)
*/
#include <iostream>
using namespace std;
int main()
{
int i,k,n;
while(scanf("%d", &n), n)
{
if(n%6!=2 && n%6!=3)
{
printf("2");
for(i=4; i<=n; i+=2)
printf(" %d", i);
for(i=1; i<=n; i+=2)
printf(" %d", i);
printf("\n");
continue;
}
k = n/2;
printf("%d", k);
if(!(k & 1) && !(n & 1))
{
for(i=k+2; i<=n; i+=2)
printf(" %d", i);
for(i=2; i<=k-2; i+=2)
printf(" %d", i);
for(i=k+3; i<=n-1; i+=2)
printf(" %d", i);
for(i=1; i<=k+1; i+=2)
printf(" %d", i);
}
else if(!(k & 1) && (n & 1))
{
for(i=k+2; i<=n-1; i+=2)
printf(" %d", i);
for(i=2; i<=k-2; i+=2)
printf(" %d", i);
for(i=k+3; i<=n-2; i+=2)
printf(" %d", i);
for(i=1; i<=k+1; i+=2)
printf(" %d", i);
printf(" %d", n);
}
else if((k & 1) && !(n & 1))
{
for(i=k+2; i<=n-1; i+=2)
printf(" %d", i);
for(i=1; i<=k-2; i+=2)
printf(" %d", i);
for(i=k+3; i<=n; i+=2)
printf(" %d", i);
for(i=2; i<=k+1; i+=2)
printf(" %d", i);
}
else if((k&1) && (n&1))
{
for(i=k+2; i<=n-2; i+=2)
printf(" %d", i);
for(i=1; i<=k-2; i+=2)
printf(" %d", i);
for(i=k+3; i<=n-1; i+=2)
printf(" %d", i);
for(i=2; i<=k+1; i+=2)
printf(" %d", i);
printf(" %d", n);
}
printf("\n");
}
return 0;
}