Wednesday, 4 October 2017

Diagonal Difference

problem-

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

solution-


#include <cmath>
#include <cstdio>
#include <vector>
#inclue <iostream>
#include <algorithm>
using namespace std;
/*
*
* Ratnadeep Sen
* National Institute Of Technology Silchar -India (NITS)
*
*/
int digdiff(vector< vector<int> > &a){
int sd=0,pd=0;
for(int i=0;i<a.size();i++){pd+=a[i][i];}
for(int i=a.size()-1, j=0 ; i>=0 && j<a.size(); i--,j++) {sd+=a[i][j];}
return abs(pd-sd);
}
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<<digdiff(a);
return 0;
}


No comments:

Post a Comment

Between two sets

problem- Consider two sets of positive integers,   and  . We say that a positive integer,  , is  between  sets   and   if the followi...