Archive/Code_HackerRank 2018. 1. 17. 00:34

[HackerRank]Diagonal Difference

Given a square matrix of size , calculate the absolute difference between the sums of its diagonals.

Input Format

The first line contains a single integer, . The next  lines denote the matrix's rows, with each line containing space-separated integers describing the columns.

Constraints

Output Format

Print the absolute difference between the two sums of the matrix's diagonals as a single integer.

Sample Input

3
11 2 4
4 5 6
10 8 -12

Sample Output

15

Explanation

The primary diagonal is:

11
   5
     -12

Sum across the primary diagonal: 11 + 5 - 12 = 4

The secondary diagonal is:

     4
   5
10

Sum across the secondary diagonal: 4 + 5 + 10 = 19 
Difference: |4 - 19| = 15

Note: |x| is absolute value function


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
 
int func(int n, vector<vector<int>> a){
    int ans;
    int a1=0;
    int a2=0;
    for(int i=0; i<n; i++){
        a1 += a[i][i];
    }
    int tmp = n-1;
    for(int i=0; i<n; i++){
        a2 += a[i][tmp-i];
    }
    
    ans = abs(a1-a2);
    
 
    return ans;
}
 
int main(){
    int n;
    cin >> n;
    vector< vector<int> > a(n,vector<int>(n));
    for(int a_i = 0;a_i < n;a_i++){
       for(int a_j = 0;a_j < n;a_j++){
          cin >> a[a_i][a_j];
       }
    }
    
    cout << func(n,a);
    
    return 0;
}
 
cs




Comment


vector<vector<int>>는 쉽게말해 int형 2차원 배열과 같다고 생각했다. 때문에 row와 column 의 index가 같은 값을 더한 후, row와 column값이 반대인 값을 더해 그 차이를 구한 뒤 절대값을 씌워주니 답이 나왔다.

2중 반복문을 쓰지 않고 필요한 값을 모두 뽑아낼 수 있다.

'Archive > Code_HackerRank' 카테고리의 다른 글

[HackerRank]Staircase  (0) 2018.01.17
[HackerRank]Plus Minus  (0) 2018.01.17
[HackerRank]A Very Big Sum  (0) 2018.01.17
[HackerRank]Compare the Triplets  (0) 2018.01.17
[HackerRank]Simple Array Sum  (0) 2018.01.17