版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/monochrome00/article/details/88996874
题目链接<http://10.7.88.2/CLanguage/showproblem?problem_id=2274>
题意:
给出一张由矩阵,求出所有合法矩阵的面积之和。
题解:
这是一个常见的套路。
先预处理出一个数组dp,记录每个点向上最大的合法高度。
对于每一行,维护底在这一行的矩阵的面积和。从左往右扫,利用单调栈维护高度。对于答案的更新只在pop的时候进行。
如果当前列高大于栈顶,直接丢进去;如果相等就跳过。
如果当前列高小于栈顶,如下图:
就应该把栈顶跳出并更新:
此时绿色部分是原先栈内的,现在就相当于这部分被pop了,这段的答案就应该更新。
首先考虑高度为1,宽度为x的所有子矩阵面积和,应该是:
乘进去然后拆开,变成:
前面两个是等差,第三个是个公式(证明百度),最后化简为:
这样的话,绿色部分的答案应该是:
同样的道理,对于最后形成的栈也要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);
}