Quadrant Sums
National Olympiad — Municipal round
Submission name: quad.cpp
Problem summary
Cells of an N by M matrix are numbered row by row from 1. Cell K is the origin; its row and column are the coordinate axes. Sum values strictly inside the four usual Cartesian quadrants, with positive horizontal direction right and positive vertical direction up.
Input
N M K, then N rows of M integers.
Output
Four sums in quadrant order I, II, III, IV.
Constraints
1 ≤ N,M ≤ 100; 1 ≤ K ≤ NM; values from −1000 to 1000.
Worked example
An independently prepared example for this explanation.
Input
3 3 5 1 2 3 4 5 6 7 8 9
Output
3 1 7 9
Solution analysis
- Convert K to zero-based row and column.
- Skip cells on either axis. Classify each remaining cell by whether it lies above/below and left/right of the origin.
Why it works
These four comparisons partition all non-axis cells into exactly the required quadrants, so each value contributes once to the appropriate sum.
Watch out. The origin row and column contribute to no quadrant.
Commented C++17 solution
An independently written complete program with standard headers.
#include<iostream>
using namespace std;
int main(){
int n,m,k;
cin>>n>>m>>k;
int r=(k-1)/m,c=(k-1)%m;
long long s[4]={};
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
int x;
cin>>x;
if(i==r||j==c){
continue; // Axes are excluded.
}
int q=i<r?(j>c?0:1):(j<c?2:3);
s[q]+=x;
}
}
for(int q=0;q<4;q++){
cout<<s[q]<<(q==3?'\n':' ');
}
}