CF1333E Road to 1600

· · 题解

思路

发现 N \times N 网格上的问题都可以转换为 4 \times 4 网格上的问题。

这是一个像 @sLMxf 一样可爱的网格。

我们用螺旋法把她拓展成 5 \times 5 的。

甚至是 6 \times 6 的。

发现都可以转换为前面问题的答案。

所以所有的问题都可转换为 4 \times 4 的问题,3 \times 3 的可以暴力,1 \le N \le 2 的情况可以证明是无解的。

代码

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int MAXN = 510;
int a[MAXN][MAXN],n;
signed main()
{
    cin >> n;
    if(n<=2){
        cout<<-1;
        return 0;
    }
    if(n == 3){
        cout<<"1 7 9\n3 2 5 \n4 8 6 ";
        return 0;
    }
    int cnt  = 0,lst = 1;
    for(int i=1;i+4<=n;i++){
        if(i % 2){
            for(int j = 1;j<=n;j++){
                a[i][j] = ++cnt;
                lst = j;
            }
        }
        else{
            for(int j = n;j>0;j--){
                a[i][j] = ++cnt;
                lst = j;
            }
        }
    }
    if(lst == 1){
        for(int j=1;j+4<=n;j++){
            if(j % 2 == 1){
                for(int i=n-3;i<=n;i++){
                    if(j+4 ==n and i == n-1) continue;
                    a[i][j] = ++cnt;
                }
                if(j+4 == n) a[n-1][j] = ++cnt;
            }
            else{
                for(int i = n;i>=n-3;i--){
                    if(j+4 == n and i == n-1) continue;
                    a[i][j] = ++cnt;
                }
                if(j+4 == n) a[n-1][j] = ++cnt;
            }
        }
        /*
4 3 6 12 
7 5 9 15 
14 1 11 10 
13 8 16 2 
*/
        a[n - 3][n-3] = 4 + cnt;a[n-3][n-2] = 3 + cnt;a[n-3][n-1] = 6 +cnt;a[n-3][n] = 12 + cnt;
        a[n - 2][n-3] = 7 + cnt;a[n-2][n-2] = 5 + cnt;a[n-2][n-1] = 9 +cnt;a[n-2][n] = 15 + cnt;
        a[n - 1][n-3] = 14 + cnt;a[n-1][n-2] = 1 + cnt;a[n-1][n-1] = 11 +cnt;a[n-1][n] = 10 + cnt;
        a[n - 0][n-3] = 13 + cnt;a[n-0][n-2] = 8 + cnt;a[n-0][n-1] = 16 +cnt;a[n-0][n] = 2 + cnt;
    }
    else{
        for(int j=n;j>4;j--){
            if(j % 2 == 1){
                for(int i=n-3;i<=n;i++){
                    if(j == 5 and i == n-1) continue;
                    a[i][j] = ++cnt;
                }
                if(j == 5) a[n-1][5] = ++cnt;
            }
            else{
                for(int i = n;i>=n-3;i--){
                    if(j == 5 and i == n-1) continue;
                    a[i][j] = ++cnt;
                }
                if(j == 5) a[n-1][5] = ++cnt;
            }
        }
        a[n - 3][1] = 4 + cnt;a[n-3][2] = 3 + cnt;a[n-3][3] = 6 +cnt;a[n-3][4] = 12 + cnt;
        a[n - 2][1] = 7 + cnt;a[n-2][2] = 5 + cnt;a[n-2][3] = 9 +cnt;a[n-2][4] = 15 + cnt;
        a[n - 1][1] = 14 + cnt;a[n-1][2] = 1 + cnt;a[n-1][3] = 11 +cnt;a[n-1][4] = 10 + cnt;
        a[n - 0][1] = 13 + cnt;a[n-0][2] = 8 + cnt;a[n-0][3] = 16 +cnt;a[n-0][4] = 2 + cnt;
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cout<<a[i][j] <<" ";
        }
        cout<<"\n";
    }
    return 0;
 }