洛谷 P3400 仓鼠窝

题目描述
萌萌哒的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);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值