[NOIP 2015] 神奇的幻方
[题目链接]
[算法]
按照题意模拟即可,时间复杂度O(N^2)
[代码]
#include<bits/stdc++.h> using namespace std; #define MAXN 50 int i,j,n; int a[MAXN][MAXN]; pair<int,int> pos[MAXN * MAXN]; template <typename T> inline void read(T &x) { long long f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } int main() { read(n); a[1][n / 2 + 1] = 1; pos[1] = make_pair(1,n / 2 + 1); for (i = 2; i <= n * n; i++) { if (pos[i - 1].first == 1 && pos[i - 1].second != n) { a[n][pos[i - 1].second + 1] = i; pos[i] = make_pair(n,pos[i - 1].second + 1); } if (pos[i - 1].second == n && pos[i - 1].first != 1) { a[pos[i - 1].first - 1][1] = i; pos[i] = make_pair(pos[i - 1].first - 1,1); } if (pos[i - 1].first == 1 && pos[i - 1].second == n) { a[2][pos[i - 1].second] = i; pos[i] = make_pair(2,pos[i - 1].second); } if (pos[i - 1].first != 1 && pos[i - 1].second != n) { if (!a[pos[i - 1].first - 1][pos[i - 1].second + 1]) { a[pos[i - 1].first - 1][pos[i - 1].second + 1] = i; pos[i] = make_pair(pos[i - 1].first - 1,pos[i - 1].second + 1); } else { a[pos[i - 1].first + 1][pos[i - 1].second] = i; pos[i] = make_pair(pos[i - 1].first + 1,pos[i - 1].second); } } } for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { printf("%d ",a[i][j]); } printf("\n"); } return 0; }