神奇的幻方
传送门:https://www.luogu.org/problemnew/show/P2615#sub
模拟即可(并不是bb机说的
#include<cstdio> using namespace std; int n,a[40][40]; struct node { int x,y; }last[1600];//记录上一个元素的位置 int main() { scanf("%d",&n); a[1][n/2+1] = 1; last[1].x = 1; last[1].y = n/2+1; for(int i = 2;i <= n*n;i++) { if(last[i-1].x == 1 && last[i-1].y != n) { a[n][last[i-1].y+1] = i; last[i].x = n; last[i].y = last[i-1].y+1; } else if(last[i-1].x != 1 && last[i-1].y == n) { a[last[i-1].x-1][1] = i; last[i].x = last[i-1].x-1; last[i].y = 1; } else if(last[i-1].x == 1 && last[i-1].y == n) { a[2][n] = i; last[i].x = 2; last[i].y = n; } else if(last[i-1].x != 1 && last[i-1].y != n) { if(a[last[i-1].x-1][last[i-1].y+1] == 0) { a[last[i-1].x-1][last[i-1].y+1] = i; last[i].x = last[i-1].x-1; last[i].y = last[i-1].y+1; } else { a[last[i-1].x+1][last[i-1].y] = i; last[i].x = last[i-1].x+1; last[i].y = last[i-1].y; } } } for(int i = 1;i <= n;i++) { for(int j = 1;j <= n;j++) { printf("%d ",a[i][j]); } printf("\n"); } return 0; }