[Simulation][NOIP2015]The Magic Square

magic magic square

 

Topic description

 

A magic square is a magical N∗ N matrix: it consists of the numbers 1, 2, 3, … , N ∗ N, and the sum of the numbers in each row, column, and two diagonals is the same.
When N is odd, we can construct a magic square by
first writing 1 in the middle of the first row.
After that, fill in each number K(K = 2,3, … , N ∗ N) in order from small to large as follows:
1. If (K − 1) is in the first row but not in the last column, then fill in K in The last row, the right column of the column where (K− 1) is located;
2. If (K − 1) is in the last column but not the first row, then fill in K in the first column, the row above the row where (K -1) is located ;
3. If (K − 1) is in the first row and last column, then fill in K just below (K� − 1);
4. If (K − 1) is neither in the first row nor in the last column, If the upper right of (K− 1) is not already filled,
then fill K at the upper right of (K − 1), otherwise fill K directly below (K− 1).
Now given N, construct the magic square of N*N as above.

 

enter

 

The input file name is magic.in.
The input file has only one line and contains an integer N, the size of the magic square.

 

output

 

The output file is named magic.out.
The output file contains N lines, each with N integers, that is, the magic square of N*N constructed as above. Separate two adjacent integers with a single space.

 

sample input

 

3

 

Sample output

 

8 1 6
3 5 7
4 9 2

 

hint

 

 

For 100% of the data, 1 ≤ N ≤ 39 and N is odd.

 

Code:

 1 #include<iostream>  
 2 #include<cstdio>  
 3 #include<cstring>  
 4 using namespace std;  
 5 int Map[100][100];  
 6 
 7 int main()  
 8 {  
 9     int i, j, n, k;  
10     scanf("%d", &n); 
11     Map[1][(n + 1) / 2] = 1;
12     i = 1; 
13     j = (n + 1) / 2;  
14     for (k = 2; k <= n * n; k++) {
15         if (i == 1 && j != n) {  
16             Map[n][j + 1] = k;  
17             i = n; 
18             j++;  
19             continue;
20         }  
21         if (j == n && i != 1) {
22             Map[i - 1][1] = k;  
23             i--; 
24             j = 1;  
25             continue;  
26         }  
27         if (i == 1 && j == n) {
28             Map[i + 1][j] = k;  
29             i++;
30             continue;  
31         }  
32         if (i != 1 && j != n) {  
33             if (Map[i - 1][j + 1] == 0) {  
34                 Map[i - 1][j + 1] = k;  
35                 i--; 
36                 j++;  
37             }  
38             else {  
39                 Map[i + 1][j] = k;  
40                 i++;  
41             }  
42         }  
43     }  
44     for (i = 1; i <= n; i++) {  
45         for (j = 1; j < n; j++) {
46             printf("%d ", Map[i][j]); 
47         }
48         printf("%d\n", Map[i][j]); 
49     }  
50     return 0;  
51 }

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324821835&siteId=291194637