← All coding problems
Diagonal Sums of a Matrix
easyMatrix+10 XPTime limit 2s
For a square n × n matrix print three numbers:
- the sum of the main diagonal (top-left to bottom-right),
- the sum of the anti-diagonal (top-right to bottom-left),
- the sum of all cells that lie on at least one of the two diagonals — a cell on both is counted only once.
Input:
- line 1:
n n - next
nlines:nintegers each
Output: the three sums on one line.
Constraints: 1 ≤ n ≤ 500, −10⁹ ≤ value ≤ 10⁹ (use 64-bit integers).
Think about it: the main diagonal is a[i][i], the anti-diagonal is a[i][n−1−i]. They share a cell only when n is odd — the centre, which you must subtract once.
Sample input 1
3 3 1 2 3 4 5 6 7 8 9
Sample output 1
15 15 25
Sample input 2
4 4 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
Sample output 2
4 4 8
Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).