洛谷 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);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章