【问题描述】
给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。例如,当给定数字序列为 0,1,0,2,1,0,1,3,2,1,2,1 时,柱子高度图如下所示,最多可以接 6 个单位的雨水。
【输入格式】
第一行包含整数 n。
第二行包含 n 个非负整数。
【输出格式】
输出一个整数,表示最大接水量。
【数据范围】
1≤n≤100000,
序列中元素均不大于 1000。
【输入样例】
12
0 1 0 2 1 0 1 3 2 1 2 1
【输出样例】
6
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int h[maxn]; //obstacle height
int stk[maxn]; //monotonous stack
int n;
int main() {
cin>>n;
for(int i=0; i<n; i++)
cin>>h[i];
int ans=0;
int top=-1; //top:pointer of stack top
//stk[top]:obstacle number
//h[stk[top]] represents the height of the obstacle with number stk[top]
//Before deleting a shorter obstacle,
//calculate its water storage relative to the previous obstacle
//The rainwater capacity between two obstacles=
//the height difference between two obstacles*
//the distance between two obstacles
for(int i=0; i<n; i++) {
int last=0;
while(top>=0 && h[stk[top]]<h[i]) {
ans+=(h[stk[top]]-last)*(i-stk[top]-1);
last=h[stk[top]];
top--;
}
if(top>=0) ans+=(h[i]-last)*(i-stk[top]-1);
stk[++top]=i;
}
cout<<ans<<endl;
return 0;
}
/*
12
0 1 0 2 1 0 1 3 2 1 2 1
6
*/
【参考文献】
https://blog.csdn.net/liudongshizhang/article/details/108034437
https://www.acwing.com/problem/content/1576/