Mike and Matrices

Description:

"Mike is given a matrix A, N and M are numbers of rows and columns respectively. A1, 1 is the number in the top left corner. All the numbers in A are non-negative integers. He also has L pairs of integers (ik, jk). His task is to calculate Ai1, j1 + Ai2, j2 + ... + AiL, jL. Unfortunately, Mike forgot if Ai, j was a number in the i'th row and j'th column or vice versa, if Ai, j was a number in the j'th row and i'th column. So, Mike decided to calculate both E1 = Ai1, j1 + Ai2, j2 + ... + AiL, jL and E2 = Aj1, i1 + Aj2, i2 + ... + AjL, iL. If it is impossible to calculate E1(i.e. one of the summands doesn't exist), then let's assume, that it is equal to -1. If it is impossible to calculate E2, then let's also assume, that it is equal to -1. Your task is to calculate max(E1, E2). Input The first line contains two integers N and M, denoting the number of rows and the number of columns respectively. Each of next N lines contains M integers. The j'th integer in the (i + 1)'th line of the input denotes Ai, j. The (N + 2)'th line contains an integer L, denoting the number of pairs of integers, that Mike has. Each of next L lines contains a pair of integers. The (N + 2 + k)-th line in the input contains a pair (ik, jk). Output The first line should contain an integer, denoting max(E1, E2)." Test Case 1 Input (stdin) 3 2 1 2 4 5 7 0 2 1 2 2 2 Expected Output 9 Test Case 2 Input (stdin) 1 3 1 2 3 2 1 3 3 1 Expected Output -1

Program :


#include<stdio.h>

#define ll long long int


int main(){

int i, j, n, m;

scanf("%d%d", &n, &m);

int arr[n][m];

for(i=0; i<n; i++)

for(j=0; j<m; j++)

scanf("%d", &arr[i][j]);

int q, f1=0, f2=0;

ll sum1=0, sum2=0;

scanf("%d", &q);

for(i=0; i<q; i++){

int l, r;

scanf("%d%d", &l, &r);

if(f1==0 && l<=n && r<=m)

sum1+=arr[l-1][r-1];

else{

f1=1;

sum1=-1;

}

if(f2==0 && r<=n && l<=m)

sum2+=arr[r-1][l-1];

else{

f2=1;

sum2=-1;

}

}

printf("%lld\n", (sum1>sum2)?sum1:sum2);

  return 0;

}