1318. Magic Square
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
If you have good observations skills, you may found that building a Magic Square is simple. A Magic Square has only an odd number N of rows and columns. For this problem you could expect the values to be 3N
15 . A Magic Square is created by integer numbers in the range from 1 to N2 , with a peculiar property, the ``sum of the numbers" in each row, column and diagonal is the same value.
For example the case for n = 3 is:
M. Square Rows Columns Diagonals 8 1 6 8+1+6 = 15 8+3+4 = 15 8+5+2 = 15 3 5 7 3+5+7 = 15 1+5+9 = 15 4+5+6 = 15 4 9 2 4+9+2 = 15 6+7+2 = 15
Input
A file with several lines, each line has the value of n .
Output
For each input line, print N and the sum in the first line, followed by the magic square. To see a nice looking square, take into account the maximum length in characters of N2 and print each number with the maximum length preceded by one space or blank character. Print one line between squares.
Sample Input
3 5
Sample Output
n=3, sum=15 8 1 6 3 5 7 4 9 2 n=5, sum=65 17 24 1 8 15 23 5 7 14 16 4 6 13 20 22 10 12 19 21 3 11 18 25 2 9
Hint
Imagine that the square is rounded. That is, the last row is connected with the first row and the last column is connected with the first column. As shown in the examples, the starting point is the center of the first row and observe how the numbers are placed following diagonals. There is only one more thing to observe, what happens when you find a cell that is already in use.
题目分析
奇数阶魔方的构造
可以查看1302获得其构造方法
注意打印的要求
#include <stdio.h>
#include <memory.h>
int main()
{
int num;
bool first = true;
while (EOF != scanf("%d", &num)) {
if (first) first = false;
else printf("\n");
int sum = (1 + num*num) / 2 * num;
int row = 0, col = num/2;
int temprow, tempcol;
int arr[num][num];
memset(arr, 0, sizeof(arr));
arr[row][col] = 1;
for (int digit = 2; digit <= num*num; ++digit) {
temprow = row != 0 ? row-1 : num-1;
tempcol = col != num-1 ? col+1 : 0;
if (arr[temprow][tempcol]) {
row = row+1;
} else {
row = temprow;
col = tempcol;
}
arr[row][col] = digit;
}
printf("n=%d, sum=%d\n", num, sum);
for (int i = 0; i < num; ++i) {
for (int j = 0; j < num; ++j) {
if (num <= 3) printf(" %d", arr[i][j]);
else if (num <= 9) printf(" %2d", arr[i][j]);
else printf(" %3d", arr[i][j]);
}
printf("\n");
}
}
}