BZOJ 3101(N皇后-N皇后O(n)構造一組解的方法)
阿新 • • 發佈:2019-02-03
3101: N皇后
Time Limit: 10 Sec Memory Limit: 128 MBSec Special JudgeSubmit: 70 Solved: 32
[Submit][Status]
Description
n*n的棋盤,在上面擺下n個皇后,使其兩兩間不能相互攻擊…
Input
一個數n
Output
第i行表示在第i行第幾列放置皇后
Sample Input
4Sample Output
24
1
3
HINT
100%的資料3<n<1000000。輸出任意一種合法解即可
Source
以下是找到的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<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<functional> #include<iostream> #include<cmath> #include<cctype> #include<ctime> using namespace std; #define For(i,n) for(int i=1;i<=n;i++) #define Fork(i,k,n) for(int i=k;i<=n;i++) #define Rep(i,n) for(int i=0;i<n;i++) #define ForD(i,n) for(int i=n;i;i--) #define RepD(i,n) for(int i=n;i>=0;i--) #define Forp(x) for(int p=pre[x];p;p=next[p]) #define Forpiter(x) for(int &p=iter[x];p;p=next[p]) #define Forstep(i,n,step) for(int i=1;i<=n;i+=step) #define Forkstep(i,k,n,step) for(int i=k;i<=n;i+=step) #define Lson (x<<1) #define Rson ((x<<1)+1) #define MEM(a) memset(a,0,sizeof(a)); #define MEMI(a) memset(a,127,sizeof(a)); #define MEMi(a) memset(a,128,sizeof(a)); #define INF (2139062143) #define F (100000007) #define MAXN (1000000+10) long long mul(long long a,long long b){return (a*b)%F;} long long add(long long a,long long b){return (a+b)%F;} long long sub(long long a,long long b){return (a-b+(a-b)/F*F+F)%F;} typedef long long ll; int a[MAXN]; int main() { // freopen("bzoj3101.in","r",stdin); // freopen(".out","w",stdout); int n,j=0; cin>>n; if (n%6!=2&&n%6!=3) { For(i,n) if (i%2==0) a[++j]=i; For(i,n) if (i%2==1) a[++j]=i; } else if (n%6==2) { int k=n>>1; for(int i=k;i<=n;i+=2) a[++j]=i; for(int i=k%2?1:2;i<=k-2;i+=2) a[++j]=i; for(int i=k+3;i<=n;i+=2) a[++j]=i; for(int i=k%2?2:1;i<=k+1;i+=2) a[++j]=i; } else if (n%6==3) { int k=n>>1; for(int i=k;i<n;i+=2) a[++j]=i; for(int i=k%2?1:2;i<=k-2;i+=2) a[++j]=i; for(int i=k+3;i<n;i+=2) a[++j]=i; for(int i=k%2?2:1;i<=k+1;i+=2) a[++j]=i; a[++j]=n; } For(i,n) printf("%d\n",a[i]); return 0; }