I've just started to learn programming so I'm asking for your understanding ;) the checking program accepts only a few tests on the rest throws the error illegal syscall and I have no ideas how to "bite it".
task: (ATTENTION, the program should be memory-saving )write a program that will find in the square matrix a diagonal with the largest sum of elements diagonals (only right). like in the picture https://i.sstatic.net/Cex9o.jpg
MAX TIME:1s, MAX memory use 3MB; input: In the first row there is a natural number n (not greater than 1000) denoting the size of the matrix A. In each of the following n lines there is a sequence of n integers (from the range -10000..10000) - these are the elements of the next row of matrix A.
output: You should write two numbers:
*the number of the diagonal matrix A, with the largest sum of elements (if there are several such numbers, the smallest of them should be printed), *the value of this sum.
like this: https://i.sstatic.net/bM7AP.jpg
I suspect that the program exceeds the required 3MB memory, so it does not pass a few tests and throws an illegal syscall error. I have no ideas how to solve this task better so please help me ;)
#include <iostream>
using namespace std;
int main(){
short length;
short counter=0;
short which=0;
int largest_sum=-10000000;
int sum=0;
cin>>length;
//matrix declaration
short **matrix = new short*[length];
for(short row=0; row<length; row++){
matrix[row] = new short [length];
}
//filling the matrix
for(short row=0; row<length; row++){
for(int column=0; column<length; column++){
cin>>matrix[row][column];
}
}
//calculating the sum of diagonals and choosing the largest one (half of all diagonals)
for(short row=length-1; row>=0; row--){
short r=row;
short c=0;
while(r<length){
sum+=matrix[r][c];
r=r+1;
c=c+1;
}
++counter;
if(sum>largest_sum){
largest_sum=sum;
which=counter;
}
sum=0;
}
//calculating the sum of diagonals and choosing the largest one (second half of all diagonals)
for(short row=1; row<length; row++){
short r=0;
short c=row;
while(c<length){
sum+=matrix[r][c];
r=r+1;
c=c+1;
}
++counter;
if(sum>largest_sum){
largest_sum=sum;
which=counter;
}
sum=0;
}
//removing from memory
for(short i=0; i<length; i++){
delete [] matrix[i];
}
delete [] matrix;
//score
cout<<which<<" "<<largest_sum;
return 0;
}
my code: https://ideone.com/6Qd1yF
some hints to improve current solution: (memory consumption ~ 2 MB)
alternative solution: (memory consumption ~10 kB)