bzoj 1657: [Usaco2006 Mar]Mooo 奶牛的歌声(单调栈)

来源:互联网 发布:程序员 网络工程师 编辑:程序博客网 时间:2024/05/16 12:14

1657: [Usaco2006 Mar]Mooo 奶牛的歌声

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 848  Solved: 594
[Submit][Status][Discuss]

Description

Farmer John的N(1<=N<=50,000)头奶牛整齐地站成一列“嚎叫”。每头奶牛有一个确定的高度h(1<=h<=2000000000),叫的音量为v (1<=v<=10000)。每头奶牛的叫声向两端传播,但在每个方向都只会被身高严格大于它的最近的一头奶牛听到,所以每个叫声都只会 被0,1,2头奶牛听到(这取决于它的两边有没有比它高的奶牛)。 一头奶牛听到的总音量为它听到的所有音量之和。自从一些奶牛遭受巨大的音量之后,Farmer John打算买一个耳罩给被残害得最厉 害的奶牛,请你帮他计算最大的总音量。

Input

* Line 1: A single integer, N.

* Lines 2..N+1: Line i+1 contains two space-separated integers, h and v, for the cow standing at location i.

    第1行:一个正整数N.

    第2到N+1行:每行包括2个用空格隔开的整数,分别代表站在队伍中第i个位置的奶牛的身高以及她唱歌时的音量.

Output

* Line 1: The loudest moo volume heard by any single cow.

    队伍中的奶牛所能听到的最高的总音量.

Sample Input

3
4 2
3 5
6 10

Sample Output

7


单调栈模板题

维护一个递减的序列,就可以求出所有在左边第一个比自己高的牛

求右边第一个比自己高的牛把数组反过来再求一次就好


#include<stdio.h>#include<stack>#include<algorithm>using namespace std;#define LL long longtypedef struct{LL val;LL h;LL col;}Line;Line s[50005];stack<int> st;int main(void){LL n, i, ans;while(scanf("%lld", &n)!=EOF){ans = 0;for(i=1;i<=n;i++){scanf("%lld%lld", &s[i].h, &s[i].val);s[i].col = 0;}for(i=1;i<=n;i++){while(st.empty()==0 && s[st.top()].h<=s[i].h)st.pop();if(st.empty()==0)s[st.top()].col += s[i].val;st.push(i);}while(st.empty()==0)st.pop();for(i=n;i>=1;i--){while(st.empty()==0 && s[st.top()].h<=s[i].h)st.pop();if(st.empty()==0)s[st.top()].col += s[i].val;st.push(i);}while(st.empty()==0)st.pop();for(i=1;i<=n;i++)ans = max(ans, s[i].col);printf("%lld\n", ans);}return 0;}


阅读全文
1 0
原创粉丝点击