洛谷 P3400 仓鼠窝

来源:互联网 发布:iphone6软件安装目录 编辑:程序博客网 时间:2024/06/11 16:25

题目描述
萌萌哒的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 registerusing 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 0
原创粉丝点击