题意:给出正方形棋盘边长n(最大300),要求输出一种摆放n皇后不冲突的方案。
分析:
数据范围较大,只能用构造的方法,不能用搜索。
下面用一个数列表示一种方案,第i个数表示棋盘第i行上的皇后所在的列号
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为奇数)
第二种情况可以认为是,当n为奇数时用最后一个棋子占据最后一行的最后一个位置,然后用n-1个棋子去填充n-1的棋盘,这样就转化为了相同类型且n为偶数的问题。
若k为奇数,则数列的前半部分均为奇数,否则前半部分均为偶数。
View Code
#include
<
iostream
>
#include
<
cstdio
>
#include
<
cstdlib
>
#include
<
cstring
>
using
namespace
std;
int
n;
int
main()
{
//
freopen("t.txt", "r", stdin);
while
(scanf(
"
%d
"
,
&
n), n)
{
if
(n
%
6
!=
2
&&
n
%
6
!=
3
)
{
printf(
"
2
"
);
for
(
int
i
=
4
; i
<=
n; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
1
; i
<=
n; i
+=
2
)
printf(
"
%d
"
, i);
putchar(
'
\n
'
);
continue
;
}
int
k
=
n
/
2
;
printf(
"
%d
"
, k);
if
(
!
(k
&
1
)
&&
!
(n
&
1
))
{
for
(
int
i
=
k
+
2
; i
<=
n; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
2
; i
<=
k
-
2
; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
k
+
3
; i
<=
n
-
1
; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
1
; i
<=
k
+
1
; i
+=
2
)
printf(
"
%d
"
, i);
}
else
if
(
!
(k
&
1
)
&&
(n
&
1
))
{
for
(
int
i
=
k
+
2
; i
<=
n
-
1
; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
2
; i
<=
k
-
2
; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
k
+
3
; i
<=
n
-
2
; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
1
; i
<=
k
+
1
; i
+=
2
)
printf(
"
%d
"
, i);
printf(
"
%d
"
, n);
}
else
if
((k
&
1
)
&&
!
(n
&
1
))
{
for
(
int
i
=
k
+
2
; i
<=
n
-
1
; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
1
; i
<=
k
-
2
; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
k
+
3
; i
<=
n; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
2
; i
<=
k
+
1
; i
+=
2
)
printf(
"
%d
"
, i);
}
else
if
((k
&
1
)
&&
(n
&
1
))
{
for
(
int
i
=
k
+
2
; i
<=
n
-
2
; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
1
; i
<=
k
-
2
; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
k
+
3
; i
<=
n
-
1
; i
+=
2
)
printf(
"
%d
"
, i);
for
(
int
i
=
2
; i
<=
k
+
1
; i
+=
2
)
printf(
"
%d
"
, i);
printf(
"
%d
"
, n);
}
putchar(
'
\n
'
);
}
return
0
;
}