接雨水(单调栈)

【问题描述】
给定 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/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值