BZOJ 3101: N皇后 构造

3101: N皇后

题目连接:

http://www.lydsy.com/JudgeOnline/problem.php?id=3101

Description

n*n的棋盘,在上面摆下n个皇后,使其两两间不能相互攻击….

Input

一个数n

Output

第i行表示在第i行第几列放置皇后

Sample Input

4

Sample Output

2

4

1

3

Hint

100%的数据3<n<1000000。输出任意一种合法解即可

题意

题解:

不要问我这结论哪儿来的,我也不知道

以下是找到的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<bits/stdc++.h>
using namespace std;

int main()
{
    int n;scanf("%d",&n);
    if(n%6!=2&&n%6!=3)
    {
        for(int i=2;i<=n;i+=2)
            printf("%d\n",i);
        for(int i=1;i<=n;i+=2)
            printf("%d\n",i);
        return 0;
    }
    else
    {
        int k=n/2;
        if(k%2==0&&n%2==0)
        {
            for(int i=k;i<=n;i+=2)
                printf("%d\n",i);
            for(int i=2;i<=k-2;i+=2)
                printf("%d\n",i);
            for(int i=k+3;i<=n-1;i+=2)
                printf("%d\n",i);
            for(int i=1;i<=k+1;i+=2)
                printf("%d\n",i);
        }
        else if(k%2==0&&n%2==1)
        {
            for(int i=k;i<n;i+=2)
                printf("%d\n",i);
            for(int i=2;i<=k-2;i+=2)
                printf("%d\n",i);
            for(int i=k+3;i<=n-2;i+=2)
                printf("%d\n",i);
            for(int i=1;i<=k+1;i+=2)
                printf("%d\n",i);
            printf("%d\n",n);
        }
        else if(k%2==1&&n%2==0)
        {
            for(int i=k;i<n;i+=2)
                printf("%d\n",i);
            for(int i=1;i<=k-2;i+=2)
                printf("%d\n",i);
            for(int i=k+3;i<=n;i+=2)
                printf("%d\n",i);
            for(int i=2;i<=k+1;i+=2)
                printf("%d\n",i);
        }
        else
        {
            for(int i=k;i<=n-2;i+=2)
                printf("%d\n",i);
            for(int i=1;i<=k-2;i+=2)
                printf("%d\n",i);
            for(int i=k+3;i<=n-1;i+=2)
                printf("%d\n",i);
            for(int i=2;i<=k+1;i+=2)
                printf("%d\n",i);
            printf("%d\n",n);
        }
    }
}
posted @ 2016-08-22 15:34  qscqesze  阅读(648)  评论(0编辑  收藏  举报