zoukankan      html  css  js  c++  java
  • BZOJ 1657 [Usaco2006 Mar]Mooo 奶牛的歌声:单调栈【高度序列】

    题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1657

    题意:

      Farmer John的N(1<=N<=50,000)头奶牛整齐地站成一列“嚎叫”。

      每头奶牛有一个确定的高度h(1<=h<=2000000000),叫的音量为v (1<=v<=10000)。

      每头奶牛的叫声向两端传播,但在每个方向都只会被身高严格大于它的最近的一头奶牛听到,所以每个叫声都只会被0,1,2头奶牛听到(这取决于它的两边有没有比它高的奶牛)。

      一头奶牛听到的总音量为它听到的所有音量之和。

      自从一些奶牛遭受巨大的音量之后,Farmer John打算买一个耳罩给被残害得最厉害的奶牛,请你帮他计算最大的总音量。

    题解:

      单调栈。

      单调性:

        对于每一个位置,要找到它左边(或右边)第一个比它大的元素。

        所以从栈顶到栈底,高度依次递增。(因为如果出现下降的元素,肯定是没有用的)

      所以分别从左到右和从右到左,做两次单调栈就好了,最后统计最大的答案。

    AC Code:

     1 #include <iostream>
     2 #include <stdio.h>
     3 #include <string.h>
     4 #include <stack>
     5 #define MAX_N 50005
     6 
     7 using namespace std;
     8 
     9 int n;
    10 int ans=0;
    11 int h[MAX_N];
    12 int v[MAX_N];
    13 int tot[MAX_N];
    14 stack<int> stk;
    15 
    16 void read()
    17 {
    18     cin>>n;
    19     for(int i=0;i<n;i++)
    20     {
    21         cin>>h[i]>>v[i];
    22     }
    23 }
    24 
    25 void solve()
    26 {
    27     memset(tot,0,sizeof(tot));
    28     for(int i=0;i<n;i++)
    29     {
    30         while(!stk.empty() && h[stk.top()]<=h[i]) stk.pop();
    31         if(!stk.empty()) tot[stk.top()]+=v[i];
    32         stk.push(i);
    33     }
    34     while(!stk.empty()) stk.pop();
    35     for(int i=n-1;i>=0;i--)
    36     {
    37         while(!stk.empty() && h[stk.top()]<=h[i]) stk.pop();
    38         if(!stk.empty()) tot[stk.top()]+=v[i];
    39         stk.push(i);
    40     }
    41     for(int i=0;i<n;i++)
    42     {
    43         ans=max(ans,tot[i]);
    44     }
    45 }
    46 
    47 void print()
    48 {
    49     cout<<ans<<endl;
    50 }
    51 
    52 int main()
    53 {
    54     read();
    55     solve();
    56     print();
    57 }
  • 相关阅读:
    code vs 1029 遍历问题 区间dp
    UVA 10891 Game of Sum 区间dp
    UVA 10635 Prince and Princess 最长公共子序列(nlongn)
    Codeforces Round #301 (Div. 2) D 概率DP
    LightOJ 1422 区间dp
    poj 1651 区间dp
    使用log4net+IExceptionFilter+Server酱完成异常日志信息推送
    MVC基础之控制器常见返回类型
    .NET Core中的IoC和DI
    使用Layui前端框架完成简单的增删改查
  • 原文地址:https://www.cnblogs.com/Leohh/p/7630400.html
Copyright © 2011-2022 走看看