[BZOJ1657][Usaco2006 Mar]Mooo 奶牛的歌声(单调栈)

题目描述

传送门

题解

刚开始的姿势不大对,学习了黄学长的姿势。
前后两遍单调栈。

代码

#include<iostream>
#include<cstdio>
using namespace std;
const int max_n=5e4+5;
int n,top,ans;
int f[max_n],h[max_n],v[max_n];
struct stack{int h,v;}s[max_n];
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)scanf("%d%d",&h[i],&v[i]);
    for(int i=1;i<=n;i++){
        while(top&&h[i]>s[top].h){
            f[i]+=s[top].v;
            top--;
        }
        s[++top].h=h[i];s[top].v=v[i];
    }
    top=0;
    for(int i=n;i>0;i--){
        while(top&&h[i]>s[top].h){
            f[i]+=s[top].v;
            top--;
        }
        s[++top].h=h[i];s[top].v=v[i];
    }
    for(int i=1;i<=n;i++)ans=max(f[i],ans);
    printf("%d",ans);
}

总结

单调栈再好好想想。

你可能感兴趣的:(单调栈,bzoj)