浅谈栈:https://www.cnblogs.com/AKMer/p/10278222.html
题目传送门:https://lydsy.com/JudgeOnline/problem.php?id=1657
做两遍Look Up即可。
时间复杂度:\(O(n)\)
空间复杂度:\(O(n)\)
代码如下:
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=5e4+5;
int n,top,ans;
int h[maxn],v[maxn],sound[maxn],stk[maxn];
int read() {
int x=0,f=1;char ch=getchar();
for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
return x*f;
}
int main() {
n=read();
for(int i=1;i<=n;i++)
h[i]=read(),v[i]=read();
for(int i=1;i<=n;i++) {
while(top&&h[stk[top]]<=h[i])top--;
sound[stk[top]]+=v[i],stk[++top]=i;
}top=0;
for(int i=n;i;i--) {
while(top&&h[stk[top]]<=h[i])top--;
sound[stk[top]]+=v[i],stk[++top]=i;
}
for(int i=1;i<=n;i++)
ans=max(ans,sound[i]);
printf("%d\n",ans);
return 0;
}
本文介绍了一种使用两次遍历查找数组中元素的最大累积值的方法,通过预处理和栈结构,实现时间复杂度O(n),空间复杂度O(n)的高效算法。适用于解决特定类型的问题,如计算建筑物间声音传播的最大值。

1177

被折叠的 条评论
为什么被折叠?



