Binary Search and Two Pointers related question.
For the above-mentioned question, In other people's solutions, people get AC with a binary search solution. However, I get TLE with Binary Search Solution. There might be some error in implementation and there aren't any Wrong Answers, so I can't figure out what's wrong with my solution. Other than that, I can't quite fathom the O(NM) time complexity solution which is mentioned in the editorial.
Also, what is the time complexity of this code per test case?
Any sort of help is appreciated. Thanks.
#include <bits/stdc++.h>
using namespace std;
#define f(i,a,b) for(int (i) = (a); (i) < (b); ++(i))
#define ull unsigned long long int
#define test int t;cin>>t;while(t--)
#define input(n) int (n);cin>>(n);
#define nfs ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define outl(n) cout<<(n)<<'\n';
int avg(vector<vector<ull>> v, int x,int y,int l){
ull sum=(v[x+l][y+l]+v[x-1][y-1]-v[x-1][y+l]-v[x+l][y-1]);
sum=sum/((l+1)*(l+1));
return sum;
}
int main(void){
nfs //macro
test //macro
{
// used input macro
input(n)
input(m)
input(k)
vector<vector<ull>> prefix;
f(i,0,n+1){
vector<ull> r;
f(j,0,m+1){
if(i!=0 && j!=0){
input(x)
r.push_back(x);
}
else{
r.push_back(0);
}
}
prefix.push_back(r);
}
// rowAdd
f(i,1,n+1){
f(j,1,m+1){
prefix[i][j]+=prefix[i][j-1];
}
}
// columnAdd
f(i,1,m+1){
f(j,1,n+1){
prefix[j][i]+=prefix[j-1][i];
}
}
// n*m*log(min(m,n)) loop
ull count=0;
f(i,1,n+1){
f(j,1,m+1){
int gap = min(m-j,n-i);
int L=0,R=gap;
if(avg(prefix,i,j,R)<k){
count+=0;
continue;
}
if(avg(prefix,i,j,0)>=k){
count+=gap+1;
continue;
}
while(L<R){
int mid=L+(R-L)/2;
ull avrg=avg(prefix,i,j,mid);
if(avrg>=k)R=mid;
else L=mid+1;
}
count+=gap-L+1;
}
}
cout<<(count)<<'\n';
}
return 0;
}