BJ analog matrix [monotone stack]

Topic meaning:

Given an n*m 01 matrix, ask how many all-zero sub-matrices with area greater than k are there. n,m<=4000.

Problem solving ideas:

At the beginning, I thought that using a monotonic stack to process a maximal submatrix with each point as the lower right corner would be enough to calculate a legal matrix including the lower right corner, but each point would generate O(n) maximal submatrixes, and the weight would be calculated. .
After reading the solution, you can add a height without calculating the contribution, and when the height is dropped, calculate the contribution of the part whose height is greater than the two surrounding heights in the maximal sub-matrix with it as the height. This is O ( n 2 ) .
It sounds a bit confusing, let's look at the code.

#include<bits/stdc++.h>
#define ll long long
using namespace std;
int getint()
{
    int i=0,f=1;char c;
    for(c=getchar();c!='-'&&(c<'0'||c>'9');c=getchar());
    if(c=='-')f=-1,c=getchar();
    for(;c>='0'&&c<='9';c=getchar())i=(i<<3)+(i<<1)+c-'0';
    return i*f;
}
const int N=4005;
int n,m,k,a[N][N],f[N][N],s[N],h[N];
ll ans;

int main()
{
    //freopen("lx.in","r",stdin);
    n=getint(),m=getint(),k=getint();
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        {
            f[i][j]=f[i-1][j]+f[i][j-1]-f[i-1][j-1]+(i*j>=k);
            a[i][j]=getint();
        }
    for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)f[i][j]+=f[i][j-1];
    for(int i=1,top;i<=n;i++)
    {
        top=0;
        for(int j=1;j<=m;j++)h[j]=a[i][j]?0:++h[j];
        for(int j=1;j<=m+1;j++)
        {
            while(top&&h[s[top]]>=h[j])ans+=f[h[s[top]]][j-1-s[top-1]]-f[max(h[s[top-1]],h[j])][j-1-s[top-1]],top--;
            s[++top]=j;
        }
    }
    cout<<ans<<'\n';
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324797080&siteId=291194637