思路:
主要是想清楚计算每个方向的和时加数下标的变化。
解答:
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
bool cmp(int a, int b) {
return a > b;
}
int main() {
int m;
while(scanf("%d", &m) != EOF) {
int input[m][m];
for(int i = 0; i <= m - 1; i++) {
for(int j = 0; j <= m - 1; j++) {
scanf("%d", &input[i][j]);
}
getchar();
}
int result_num = 2 * m + 2;
int result[result_num];
memset(result, 0, sizeof(result)); // 结果数组置为0
// 横向
for(int x = 0; x <= m - 1; x++) {
for(int y = 0; y <= m - 1; y++)
result[x] += input[x][y];
}
// 竖向
for(int y = 0; y <= m - 1; y++) {
for(int x = 0; x <= m - 1; x++)
result[y + m] += input[x][y];
}
// 主对角线
for(int x = 0; x <= m - 1; x++) {
result[2 * m] += input[x][x];
}
// 副对角线
for(int x = 0, y = m - 1; x <= m - 1; x++, y--) {
result[2 * m + 1] += input[x][y];
}
sort(result, result + result_num, cmp);
for(int i = 0; i <= result_num - 1; i++)
printf("%d ", result[i]);
printf("\n");
}
return 0;
}
坑:
实际上有多组输入,所以要加上while(scanf()!=EOF)。ヽ(#`Д´)ノ