【单调栈】2274 - Strah

题目链接<http://10.7.88.2/CLanguage/showproblem?problem_id=2274>


题意:

给出一张由矩阵,求出所有合法矩阵的面积之和。


题解:

这是一个常见的套路。

先预处理出一个数组dp,记录每个点向上最大的合法高度。

对于每一行,维护底在这一行的矩阵的面积和。从左往右扫,利用单调栈维护高度。对于答案的更新只在pop的时候进行。

如果当前列高大于栈顶,直接丢进去;如果相等就跳过。

如果当前列高小于栈顶,如下图:

就应该把栈顶跳出并更新:

此时绿色部分是原先栈内的,现在就相当于这部分被pop了,这段的答案就应该更新。

首先考虑高度为1,宽度为x的所有子矩阵面积和,应该是:\sum{i*(x-i+1)}

乘进去然后拆开,变成:\sum{i*x}+\sum{i}-\sum{i^2}

前面两个是等差,第三个是个公式(证明百度),最后化简为:\frac{x(x+1)(x+2)}{6}

这样的话,绿色部分的答案应该是:\frac{(h1+h2+1)*(h2-h1)}{2}*\frac{x(x+1)(x+2)}{6}

同样的道理,对于最后形成的栈也要pop,答案的计算也类似,注意一下h1的取值就行。


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e3+7;
char s[N][N];
int dp[N][N];
ll ans;
struct Node{
    int h,x;
};
ll solve(ll x,ll h1,ll h2){
    ll t1=(x*(x+1)*(x+2))/6;
    ll t2=(h1+h2+1)*(h2-h1)/2;
    return t1*t2;
}
int main(){
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++){
        scanf("%s",s[i]+1);
    }
    for(int j=1;j<=m;j++){
        if(s[1][j]=='.') dp[1][j]=1;
        else dp[1][j]=0;
    }
    for(int i=2;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(s[i][j]=='.') dp[i][j]=dp[i-1][j]+1;
            else dp[i][j]=0;
        }
    }
    stack<Node>st;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            int tmp=j;
            while(!st.empty()){
                Node t=st.top();
                if(t.h==dp[i][j]) break;
                else if(t.h<dp[i][j]){
                    st.push((Node){dp[i][j],tmp});
                    break;
                }
                else if(t.h>dp[i][j]){
                    st.pop();
                    ll h1=dp[i][j];
                    if(!st.empty()) h1=max(st.top().h,dp[i][j]);
                    ans+=solve(j-t.x,h1,t.h);
                    tmp=t.x;
                }
            }
            if(st.empty()) st.push((Node){dp[i][j],tmp});
        }
        while(!st.empty()){
            Node t=st.top();
            st.pop();
            ll x=m-t.x+1;
            if(st.empty()) ans+=solve(m-t.x+1,0,t.h);
            else ans+=solve(m-t.x+1,st.top().h,t.h);
        }
    }
    printf("%lld\n",ans);
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值