Title description
Please write a program, for a square matrix with m rows and m columns (1<m<10), find the sum of each row, each column and the main diagonal elements, and finally output in order from largest to smallest.
enter
There is a set of data. The first line of the input is a positive integer, representing m, and the next m lines, m integers in each line represent the elements of the square matrix.
Output
A line of integers arranged from largest to smallest, each integer followed by a space, and finally a new line.
Sample input Copy
4 15 8 -2 6 31 24 18 71 -3 -9 27 13 17 21 38 69
Sample output Copy
159 145 144 135 81 60 44 32 28 27
AC code
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
//res为结果数组
int a[10][10];
int res1[10];
int res2[10];
int res[10];
bool cmp(int a,int b)
{
return a > b;
}
int main()
{
int m;
while (scanf("%d",&m) != EOF)
{
int j;
//接收元素
for (int i = 0;i < m;i++)
for (int j = 0;j < m;j++)
scanf("%d",&a[i][j]);
//每一行元素和,第i行元素和存放在res[i]中
//注意:对于多组测试数据,每次要初始化数组,下面同理
memset(res1,0,sizeof res1);
for (int i = 0;i < m;i++)
for (int j = 0;j < m;j++)
res1[i] += a[i][j];
//每一列元素和
memset(res2,0,sizeof res2);
for (int i = 0;i < m;i++)
for (int j = 0;j < m;j++)
res2[i] += a[j][i];
//主对角线元素和
int sum1 = 0;
for (int i = 0;i < m;i++)
{
j = i;
sum1 += a[i][j];
}
//副对角线元素和
int sum2 = 0;
for (int i = 0;i < m;i++)
{
j = m - i - 1;
sum2 += a[i][j];
}
//将所有数据搬到res结果数组中
j = 0;
for (int i = 0;i < m;i++) res[j++] = res1[i];
for (int i = 0;i < m;i++) res[j++] = res2[i];
res[j++] = sum1;
res[j++] = sum2;
sort(res,res + j,cmp);
for (int i = 0;i < j;i++) printf("%d ",res[i]);
puts("");
}
return 0;
}