C - 奇数阶魔方

题目:C - 奇数阶魔方

找规律题,题目告诉你是右上角,那么先把1写到第一行的中间,然后往右上角移动(出界了就上下左右平移n个单位直到那个位置回到n*n的矩阵中),如果右上角已经有数了,那么就往下移动(出界同上处理)。至于往下移动的时候会不会还有数在那里呢?这个是不会的,我测过19都没事,至于为什么不会我就不清楚了>_<。细节看代码。

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <cstring>
 4 #include <iostream>
 5 using namespace std;
 6 typedef long long LL;
 7 
 8 const int MAXN = 20 * 20;
 9 
10 int mat[MAXN][MAXN];
11 int n;
12 
13 int youshang(int x, int y) {
14     ++x, --y;
15     if(x > n) x = 1;
16     if(y < 1) y = n;
17     return mat[y][x];
18 }
19 
20 void turn_up(int &x, int &y) {
21     ++y;
22     if(y > n) y = n;
23 }
24 
25 void turn_youshang(int &x, int &y) {
26     ++x, --y;
27     if(x > n) x = 1;
28     if(y < 1) y = n;
29 }
30 
31 int main() {
32     int T;
33     scanf("%d", &T);
34     while(T--) {
35         scanf("%d", &n);
36         memset(mat, 0, sizeof(mat));
37         int x = n / 2 + 1, y = 1;
38         for(int i = 1; i <= n * n; ++i) {
39             mat[y][x] = i;
40             if(i == n * n) break;
41             if(youshang(x, y)) turn_up(x, y);
42             else turn_youshang(x, y);
43         }
44         for(int i = 1; i <= n; ++i) {
45             for(int j = 1; j <= n; ++j) printf("%4d", mat[i][j]);
46             //rintf("%4d\n", mat[i][n]);
47             puts("");
48         }
49     }
50 }

 

posted on 2013-08-19 14:07  SCNUACM  阅读(269)  评论(1编辑  收藏  举报

导航