3101: N皇后
Time Limit: 10 Sec Memory Limit: 128 MBSec Special Judge
Submit: 70 Solved: 32
Description
n*n的棋盘,在上面摆下n个皇后,使其两两间不能相互攻击…
Input
一个数n
Output
第i行表示在第i行第几列放置皇后
Sample Input
4
Sample Output
2
4
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为奇数)
传送门: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; }
时间: 2024-10-16 16:05:55