[BZOJ1657]&&[Usaco2006 Mar]Mooo 奶牛的歌声

描述 Description

Farmer John’s N (1 <= N <= 50,000) cows are standing in a very straight row and mooing. Each cow has a unique height h in the range 1..2,000,000,000 nanometers (FJ really is a stickler for precision). Each cow moos at some volume v in the range 1..10,000. This“moo”travels across the row of cows in both directions (except for the end cows, obviously). Curiously, it is heard only by the closest cow in each direction whose height is strictly larger than that of the mooing cow (so each moo will be heard by 0, 1 or 2 other cows, depending on not whether or taller cows exist to the mooing cow’s right or left). The total moo volume heard by given cow is the sum of all the moo volumes v for all cows whose mooing reaches the cow. Since some (presumably taller) cows might be subjected to a very large moo volume, FJ wants to buy earmuffs for the cow whose hearing is most threatened. Please compute the loudest moo volume heard by any cow.

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

输入格式 InputFormat

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 个位置的奶牛的身高以及她唱歌时的音量.

输出格式 OutputFormat

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


样例输入 SampleInput

12 16
3 11
10 14
2 7
16 5
18 18
14 18
17 2
1 8
9 17
6 13
11 8
20 14
7 13
13 11
5 13
19 11
4 13
15 9
8 4

样例输出 SampleOutput


来源 Source


BZOJ 1657

代码 Code

单调栈从左右各扫一遍。话说 STL 中的 stack,queue,priority_queue 都没有那种用来一次性清空的函数么。。。

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <algorithm> 
#include <cmath>
#include <stack>
using namespace std;
struct cow
    int h,id,v;
    bool operator < (const cow &temp) const
        return h<temp.h;
cow a[50005];
stack <cow> q;
int f[50005];
int i,j,t,n,m,l,r,k,z,y,x;
inline int read()
    int x=0;char ch=getchar();
    while (ch<'0' || ch>'9') ch=getchar();
    while (ch>='0' && ch<='9') x=x*10+ch-'0',ch=getchar();
    return x;
int main()
    for (i=1;i<=n;i++) a[i].h=read(),a[i].v=read(),a[i].id=i;
    for (i=2;i<=n;i++)
        while (!q.empty() && q.top().h<=a[i].h) q.pop();
        if (!q.empty()) f[q.top().id]+=a[i].v;
    while (!q.empty()) q.pop();
    for (i=n-1;i>=1;i--)
        while (!q.empty() && q.top().h<=a[i].h) q.pop();
        if (!q.empty()) f[q.top().id]+=a[i].v;
    int ans=0;
    for (i=1;i<=n;i++) ans=max(ans,f[i]);
    return 0;