D1T1> 神奇的幻方
模拟即可。
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #define rep(i, a, b) for (int i = a; i <= b; i++) 5 #define drep(i, a, b) for (int i = a; i >= b; i--) 6 #define REP(i, a, b) for (int i = a; i < b; i++) 7 #define pb push_back 8 #define mp make_pair 9 #define clr(x) memset(x, 0, sizeof(x)) 10 #define xx first 11 #define yy second 12 13 using namespace std; 14 15 typedef long long i64; 16 typedef pair<int, int> pii; 17 const int inf = ~0U >> 1; 18 const i64 INF = ~0ULL >> 1; 19 //****************************** 20 21 int map[55][55]; 22 int main() { 23 int n; 24 scanf("%d", &n); 25 pii last = mp(1, n / 2 + 1); 26 map[1][n / 2 + 1] = 1; 27 rep(i, 2, n * n) { 28 if (last.xx == 1 && last.yy != n) { 29 map[n][last.yy + 1] = i; 30 last = mp(n, last.yy + 1); 31 } 32 else if (last.yy == n && last.xx != 1) { 33 map[last.xx - 1][1] = i; 34 last = mp(last.xx - 1, 1); 35 } 36 else if (last.xx == 1 && last.yy == n) { 37 map[last.xx + 1][last.yy] = i; 38 last = mp(last.xx + 1, last.yy); 39 } 40 else if (last.xx != 1 && last.yy != n && !map[last.xx - 1][last.yy + 1]) { 41 map[last.xx - 1][last.yy + 1] = i; 42 last = mp(last.xx - 1, last.yy + 1); 43 } 44 else { 45 map[last.xx + 1][last.yy] = i; 46 last = mp(last.xx + 1, last.yy); 47 } 48 } 49 rep(i, 1, n) { 50 rep(j, 1, n) { 51 if (j != 1) printf(" "); 52 printf("%d", map[i][j]); 53 } 54 puts(""); 55 } 56 return 0; 57 }