题目描述
萌萌哒的Created equal是一只小仓鼠,小仓鼠自然有仓鼠窝啦。
仓鼠窝是一个由n*m个格子组成的行数为n、列数为m的矩阵。小仓鼠现在想要知道,这个矩阵中有多少个子矩阵!(实际上就是有多少个子长方形嘛。)比如说有一个2*3的矩阵,那么1*1的子矩阵有6个,1*2的子矩阵有4个,1*3的子矩阵有2个,2*1的子矩阵有3个,2*2的子矩阵有2个,2*3的子矩阵有1个,所以子矩阵共有6+4+2+3+2+1=18个。
可是仓鼠窝中有的格子被破坏了。现在小仓鼠想要知道,有多少个内部不含被破坏的格子的子矩阵!
【题目分析】
单调栈,分每一排为底边的时候,然后统计一个方框之内的个数。(只可意会不可言传)。
【代码】
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll (long long)
#define reg register
using namespace std;
int map[3005][3005],h[3005][3005];
int n,m,top;
long long ans=0;
struct node{int hi,wi;}sta[4001];
int read()
{
reg int ret=0; char ch=getchar();
while (ch>'9'||ch<'0') ch=getchar();
while (ch>='0'&&ch<='9')
{
ret*=10;
ret+=ch-'0';
ch=getchar();
}
return ret;
}
int main()
{
scanf("%d%d",&n,&m);
for (reg int i=1;i<=n;++i)
for (reg int j=1;j<=m;++j)
scanf("%d",&map[i][j]);
for (reg int i=1;i<=n;++i)
for (reg int j=1;j<=m;++j)
if (map[i][j]) h[i][j]=h[i-1][j]+1;
for (reg int i=1;i<=n;++i)
{
reg int top=0;
for (reg int j=1;j<=m+1;++j)
{
while (sta[top].hi>h[i][j])
{
if ((!(top-1))||(sta[top-1].hi<h[i][j]))
{
ans+=(ll sta[top].hi-ll h[i][j])*((1+ll sta[top].wi)*(ll sta[top].wi)/2);
sta[top].hi=h[i][j];
}
else if (sta[top-1].hi>=h[i][j])
{
ans+=(ll sta[top].hi-ll sta[top-1].hi)*((1+ll sta[top].wi)*(ll sta[top].wi)/2);
top--;
sta[top].wi+=sta[top+1].wi;
}
}
if (h[i][j]==sta[top].hi) sta[top].wi++;
else
{
++top;
sta[top].hi=h[i][j];
sta[top].wi=1;
}
}
}
printf("%lld\n",ans);
}
本文介绍了一种使用单调栈计算不包含损坏格子的子矩阵数量的方法。通过遍历矩阵并利用单调栈来统计每个子矩阵的有效范围,最终计算出所有有效子矩阵的数量。
1451

被折叠的 条评论
为什么被折叠?



