双倍经验:P2615 [NOIP2015 提高组] 神奇的幻方
这道题很简单,模拟即可。
设幻方为 , 表示要填的数,则:
- 先设 为 。
- 将 填入 。
- 然后我们循环遍历直到 (想一想,为什么不是 ),执行以下操作:
- 设 为 , 为 。
- 将 减 。如果 原来是 ,那么将 设为 。
- 将 加 。如果 原来是 ,那么将 设为 。
- 这时候判断 是否填过。如果没有填,那么将 加 ,然后将 填入 ,再令 ,,跳过即可。
- 否则,还原 和 ,并将 加 。如果 原来是 ,那么将 设为 。
- 再将 加 ,填入 即可。
重复以上步骤,幻方就可以填好,代码如下(增加了防抄袭字符!):
#include <iostream>
using namespace std;
int a[23][23];
int main() {
int n;
cin >> n;
a[1][n / 2 + 1] = 1;
int cnt = 1;
int x = 1, y = n / 2 + 1;
while (cnt < n * n) {
int nx = x, ny = y;
nx = ((nx == 1) ? n : nx - 1);
ny = ((ny == n) ? 1 : ny + 1);
if (a[nx][ny] == 0) {
a[nx][ny] = ++cnt;
x = nx, y = ny;
continue;
}
nx = x, ny = y;
nx = ((nx == n) ? 1 : nx + 1);
a[nx][ny] = ++cnt;
x = nx, y = ny;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << a[i][j] << ' ';
}
cout << endl;
}
}