找规律+模拟 之 codevs 1160 蛇形矩阵

//  [10/11/2014 Sjm]
/*
(数组下标默认从 1 开始)
经分析可知:
令 myNode = ((n + 1) >> 1),
则: myArr[myNode][myNode] = 1^2
	 myArr[myNode + 1][myNode + 1] = (1 + 2)^2
	 myArr[myNode + 2][myNode + 2] = (3 + 2)^2
	 …………
	 据此可模拟生成过程。。。
*/
 1 #include <iostream>
 2 #include <cstdlib>
 3 #include <cstdio>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <functional>
 7 #include <string>
 8 #include <cstring>
 9 #include <vector>
10 #include <stack>
11 #include <queue>
12 #include <map>
13 using namespace std;
14 #define eps 1e-8
15 #define MAX_LEN 102
16 
17 int n;
18 int myArr[MAX_LEN][MAX_LEN];
19 
20 void Solve() {
21     int val = 1;
22     int myNode = ((n + 1) >> 1);
23     myArr[myNode][myNode] = val * val;
24     for (int i = myNode + 1; i <= n; ++i) {
25         val += 2;
26         myArr[i][i] = val * val;
27         int northwest = myNode - (i - myNode);
28         for (int j = 1; j < val; ++j) {
29             myArr[i][i - j] = myArr[i][i] - j;
30         }
31         for (int j = 1; j < val; ++j) {
32             myArr[i - j][northwest] = myArr[i][northwest] - j;
33         }
34         for (int j = 1; j < val; ++j) {
35             myArr[northwest][northwest + j] = myArr[northwest][northwest] - j;
36         }
37         for (int j = 1; j < (val - 1); ++j) {
38             myArr[northwest + j][i] = myArr[northwest][i] - j;
39         }
40     }
41     int Sum = 0;
42     for (int i = 1; i <= n; ++i) {
43         for (int j = 1; j <= n; ++j) {
44             printf("%d", myArr[i][j]);
45             if (j != n) printf(" ");
46             else printf("
");
47             if ((i == j) || (i + j == n + 1)) {
48                 Sum += myArr[i][j];
49             }
50         }
51     }
52     printf("%d
", Sum);
53 }
54 
55 int main() {
56     scanf("%d", &n);
57     Solve();
58     return 0;
59 }
原文地址:https://www.cnblogs.com/shijianming/p/4140796.html