BZOJ1657:[USACO2006MAR]Mooo

本文介绍了一种使用两次遍历查找数组中元素的最大累积值的方法,通过预处理和栈结构,实现时间复杂度O(n),空间复杂度O(n)的高效算法。适用于解决特定类型的问题,如计算建筑物间声音传播的最大值。

浅谈栈: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;
}

转载于:https://www.cnblogs.com/AKMer/p/10279171.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值