In this HackerEarth Unsafe elements in a matrix problem solution, You have a matrix S consisting of N rows and M columns. Let u be the maximum element of the matrix and v be the smallest element of the matrix. If any element whose value is equal to u or v is called unsafe elements and they disfigure the complete row and column of the matrix. More formally, if any element is equal to u or v and contains cell number (x, y), that is, S[x][y] = u or S[x][y] = v are unsafe so that they also disfigure all the cells that have row x or y column and also are unsafe.

Your task is to find the number of safe elements.


HackerEarth Unsafe elements in a matrix problem solution


HackerEarth Unsafe elements in a matrix problem solution.

#include<bits/stdc++.h>
using namespace std;
#define FIO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define mod 1000000007
#define test ll t; cin>>t; while(t--)
typedef long long int ll;
int main() {
FIO;
test{
ll n,m,u=LONG_MAX,v=LONG_MIN,i,j;
cin>>n>>m;
vector<vector<ll>>inp(n,vector<ll>(m));
for( i=0;i<n;i++){
for( j=0;j<m;j++){
cin>>inp[i][j];
u=min(u,inp[i][j]);
v=max(v,inp[i][j]);
}
}
ll r=0,c=0;
for(i=0;i<n;i++){
if(*max_element(inp[i].begin(),inp[i].end())!=v && *min_element(inp[i].begin(),inp[i].end())!=u){
r++;
}
}
for(i=0;i<m;i++){
ll x=LONG_MAX,y=LONG_MIN;
for(j=0;j<n;j++){
x=min(x,inp[j][i]);
y=max(y,inp[j][i]);
}
if(x!=u && y!=v){
c++;
}
}
cout<<r*c<<endl;
}
return 0;
}

Second solution

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

int main(){
ios::sync_with_stdio(0), cin.tie(0);
int t;
cin >> t;
while(t--){
int n, m;
cin >> n >> m;
vector<int> rmx(n, INT_MIN), cmx(m, INT_MIN), rmn(n, INT_MAX), cmn(m, INT_MAX);
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++){
int x;
cin >> x;
rmx[i] = max(rmx[i], x);
cmx[j] = max(cmx[j], x);
rmn[i] = min(rmn[i], x);
cmn[j] = min(cmn[j], x);
}
int mx = *max_element(rmx.begin(), rmx.end()), mn = *min_element(rmn.begin(), rmn.end());
int r = 0, c = 0;
for(int i = 0; i < n; i++)
r += rmn[i] != mn && rmx[i] != mx;
for(int i = 0; i < m; i++)
c += cmn[i] != mn && cmx[i] != mx;
cout << c * r << '\n';
}
}