洛谷P2615 神奇的幻方
大模拟..(大雾
主要是一开始写了N个循环,觉得自己脑子boom了
后来关上电脑想到了O(n)做法
C++代码:
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<string> #include<map> #include<set> #include<queue> #define INF 0x3f3f3f3f #define inf 0x3f #define ll long long using namespace std; int n,a[40][40],sum,qwq,k,x,y; int main(){ cin>>n; sum=n/2; sum++; a[1][sum]=1; qwq=n*n; x=1; y=sum; for(int i=2;i<=qwq;i++){ k=i; if(x==1&&y!=n){ a[n][y+1]=k; x=n; y++; continue; } if(y==n&&x!=1){ a[x-1][1]=k; x--; y=1; continue; } if(x==1&&y==n){ a[x+1][y]=k; x++; continue; } if(x!=1&&y!=n){ if(a[x-1][y+1]==0){ a[x-1][y+1]=k; x--; y++; } else{ a[x+1][y]=k; x++; } continue; } } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ cout<<a[i][j]<<" "; } cout<<endl; } return 0; }